Java 8 Distinct by property

后端 未结 29 1867
傲寒
傲寒 2020-11-21 22:35

In Java 8 how can I filter a collection using the Stream API by checking the distinctness of a property of each object?

For example I have a list of

29条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-21 23:17

    The easiest way to implement this is to jump on the sort feature as it already provides an optional Comparator which can be created using an element’s property. Then you have to filter duplicates out which can be done using a statefull Predicate which uses the fact that for a sorted stream all equal elements are adjacent:

    Comparator c=Comparator.comparing(Person::getName);
    stream.sorted(c).filter(new Predicate() {
        Person previous;
        public boolean test(Person p) {
          if(previous!=null && c.compare(previous, p)==0)
            return false;
          previous=p;
          return true;
        }
    })./* more stream operations here */;
    

    Of course, a statefull Predicate is not thread-safe, however if that’s your need you can move this logic into a Collector and let the stream take care of the thread-safety when using your Collector. This depends on what you want to do with the stream of distinct elements which you didn’t tell us in your question.

提交回复
热议问题