Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Distinct List of Objects

I have a list/collection of objects that may or may not have the same property values. What's the easiest way to get a distinct list of the objects with equal properties? Is one collection type best suited for this purpose? For example, in C# I could do something like the following with LINQ.

var recipients = (from recipient in recipientList
                 select recipient).Distinct();

My initial thought was to use lambdaj (link text), but it doesn't appear to support this.

like image 553
javacavaj Avatar asked Jun 19 '09 20:06

javacavaj


People also ask

How do you make a list distinct in Java?

We'll use the distinct() method from the Stream API, which returns a stream consisting of distinct elements based on the result returned by the equals() method. There we have it, three quick ways to clean up all the duplicate items from a List.

What are distinct objects in Java?

distinct() returns a stream consisting of distinct elements in a stream. distinct() is the method of Stream interface. This method uses hashCode() and equals() methods to get distinct elements. In case of ordered streams, the selection of distinct elements is stable.

What does distinct () do in Java?

Java Stream distinct() method returns a new stream of distinct elements. It's useful in removing duplicate elements from the collection before processing them.


4 Answers

return new ArrayList(new HashSet(recipients)); 
like image 139
Chase Seibert Avatar answered Oct 08 '22 10:10

Chase Seibert


Use an implementation of the interface Set<T> (class T may need a custom .equals() method, and you may have to implement that .equals() yourself). Typically a HashSet does it out of the box : it uses Object.hashCode() and Object.equals() method to compare objects. That should be unique enough for simple objects. If not, you'll have to implement T.equals() and T.hashCode() accordingly.

See Gaurav Saini's comment below for libraries helping to implement equals and hashcode.

like image 28
glmxndr Avatar answered Oct 08 '22 10:10

glmxndr


Place them in a TreeSet which holds a custom Comparator, which checks the properties you need:

SortedSet<MyObject> set = new TreeSet<MyObject>(new Comparator<MyObject>(){

    public int compare(MyObject o1, MyObject o2) {
         // return 0 if objects are equal in terms of your properties
    }
});

set.addAll(myList); // eliminate duplicates
like image 35
Robert Munteanu Avatar answered Oct 08 '22 11:10

Robert Munteanu


Java 8:

recipients = recipients.stream()
    .distinct()
    .collect(Collectors.toList());

See java.util.stream.Stream#distinct.

like image 28
Dexter Legaspi Avatar answered Oct 08 '22 10:10

Dexter Legaspi