Java - Distinct List of Objects

后端 未结 9 903
不知归路
不知归路 2020-12-05 09:41

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

相关标签:
9条回答
  • 2020-12-05 10:13

    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.

    0 讨论(0)
  • 2020-12-05 10:15

    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.

    0 讨论(0)
  • 2020-12-05 10:18
    return new ArrayList(new HashSet(recipients));
    
    0 讨论(0)
  • 2020-12-05 10:28

    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
    
    0 讨论(0)
  • 2020-12-05 10:30

    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.

    0 讨论(0)
  • 2020-12-05 10:30

    order preserving version of the above response

    return new ArrayList(new LinkedHashSet(recipients));
    
    0 讨论(0)
提交回复
热议问题