0

I'm facing a problem in Java... I have one list of object Objeto, this object has the attributes listed below:

public class Objeto{
    private FirstEntity first;
    private List<ThirdEntity> thirds;
}

I need to find the objects in this list that have the same FirstEntity attribute... How can I do this?

Thanks in advance!

2 Answers2

3

The main reason why this question is difficult to answer, is because we don't know how many possible values there are for FirstEntity to hold. For this reason, we must use a Map<FirstEntity, List<Objecto>> where, for every FirstEntity, we store a List<Objecto> that share the FirstEntity attribute.

For this to compile, you must create a getter in your Objecto class for FirstEntity:

public FirstEntity getFirstEntity() {
    return first;
}

Then, the List<Objecto> can be streamed and collected into a Map<FirstEntity, List<Objecto>>:

Map<FirstEntity, List<Objecto>> map = thirds.stream().collect(Collectors.groupingBy(Objecto::getFirstEntity));

For this to work, you must override Object#equals and Object#hashCode within FirstEntity.

Jacob G.
  • 28,856
  • 5
  • 62
  • 116
2

(As before, if you need to use Java 7 or earlier - and same discussion re. FirstEntity hashCode() and equals() as in the other answer).

Assuming we have

 List<Objecto> myObjectos;

Then the following should work:

 Map<FirstEntity, List<Objecto>> map = new HashMap<>();
 for(Objecto objecto : myObjectos){
       if(!map.containsKey(objecto.first)){
              map.put(objecto.first, new LinkedList<Objecto>());
       }
       map.get(objecto.first).add(objecto);
 }
  • Thanks for your answer! But that's not the right object... I've edited my question to illustrate better... Thanks! =) – Angular Enthusiastic May 02 '17 at 18:03
  • Not sure I understand - are you asking, for all Objectos on a List, L, which of them have a first which is another Objecto (on the list) already has? Or are you asking to "group" all Objecto's which share "first"? – dan.m was user2321368 May 02 '17 at 18:09
  • If you don't need objetos with unique attribute, just remove from the map all keys with values of size < 2. – Vasiliy Vlasov May 02 '17 at 18:26
  • @dan.mwasuser2321368 your code in for loop can be simplified to:`map.computeIfAbsent(objecto.first, (key)-> new LinkedList<>()).add(objecto)` – holi-java May 02 '17 at 18:27
  • @holi-java my answer explicitly states that it is for the case where the user is limited to Java 7. Jacob G,'s answer contains a Java 8 solution. – dan.m was user2321368 May 03 '17 at 15:44