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? I
The ordinary way of doing this would be to convert to a Set, then back to a List. But you can get fancy with Functional Java. If you liked Lamdaj, you'll love FJ.
recipients = recipients
.sort(recipientOrd)
.group(recipientOrd.equal())
.map(List.<Recipient>head_());
You'll need to have defined an ordering for recipients, recipientOrd
. Something like:
Ord<Recipient> recipientOrd = ord(new F2<Recipient, Recipient, Ordering>() {
public Ordering f(Recipient r1, Recipient r2) {
return stringOrd.compare(r1.getEmailAddress(), r2.getEmailAddress());
}
});
Works even if you don't have control of equals()
and hashCode()
on the Recipient class.
You can use a Set
. There's couple of implementations:
HashSet
uses an object's hashCode
and equals
.TreeSet
uses compareTo
(defined by Comparable
) or compare
(defined by Comparator
). Keep in mind that the comparison must be consistent with equals
. See TreeSet
JavaDocs for more info.Also keep in mind that if you override equals
you must override hashCode
such that two equals objects has the same hash code.
return new ArrayList(new HashSet(recipients));
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
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.
order preserving version of the above response
return new ArrayList(new LinkedHashSet(recipients));