Java 8 Distinct by property

后端 未结 29 1833
傲寒
傲寒 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:05

    You can use the distinct(HashingStrategy) method in Eclipse Collections.

    List persons = ...;
    MutableList distinct =
        ListIterate.distinct(persons, HashingStrategies.fromFunction(Person::getName));
    

    If you can refactor persons to implement an Eclipse Collections interface, you can call the method directly on the list.

    MutableList persons = ...;
    MutableList distinct =
        persons.distinct(HashingStrategies.fromFunction(Person::getName));
    

    HashingStrategy is simply a strategy interface that allows you to define custom implementations of equals and hashcode.

    public interface HashingStrategy
    {
        int computeHashCode(E object);
        boolean equals(E object1, E object2);
    }
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题