Utils.java
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;
}
使用
List<Person> distinctElements = list.stream()
.filter(Utils.distinctByKey(Person::getId))
.collect( Collectors.toList() );