Java introduced the powerful Stream API to support functional-style operations. This tutorial will show how to find distinct elements of Stream by property or attribute.
Find distinct elements natively
Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.
1 2 3 4 5 |
Collection<String> list = ...; List<String> distinctElements = list.stream() .distinct() .collect(Collectors.toList()); |
Java Stream distinct by property
Sometimes, we want to filter our list on element property or attribute. Below how to perform that :
1 2 3 4 |
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) { Map<Object, Boolean> map = new ConcurrentHashMap<>(); return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } |
And the usage :
1 2 3 |
List<Animal> distinctElements = list.stream() .filter( distinctByKey(Animal::getId) ) .collect( Collectors.toList() ); |
That’s it.