Java 8 Distinct by property

后端 未结 29 1860
傲寒
傲寒 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 22:57

    Late to the party but I sometimes use this one-liner as an equivalent:

    ((Function) Value::getKey).andThen(new HashSet<>()::add)::apply
    

    The expression is a Predicate but since the map is inline, it works as a filter. This is of course less readable but sometimes it can be helpful to avoid the method.

提交回复
热议问题