Angular Enthusiastic
Angular Enthusiastic

Reputation: 19

How to get duplicate objects on ArrayList?

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!

Upvotes: 0

Views: 413

Answers (2)

Jacob G.
Jacob G.

Reputation: 29680

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.

Upvotes: 3

dan.m was user2321368
dan.m was user2321368

Reputation: 1705

(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);
 }

Upvotes: 2

Related Questions