Java - Distinct List of Objects

后端 未结 9 932
不知归路
不知归路 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.head_());
    

    You'll need to have defined an ordering for recipients, recipientOrd. Something like:

    Ord recipientOrd = ord(new F2() {
      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.

提交回复
热议问题