跳至主要內容

[java] java 8 distinct


public static Predicate distinctByKey(Function keyExtractor) {
Map seen = new ConcurrentHashMap<>();
return object -> seen.putIfAbsent(keyExtractor.apply(object), Boolean.TRUE) == null;
}
users.stream().filter(distinctByKey(User::getName)).collect(Collectors.toList());

reference: https://www.wanaright.com/2016/12/17/java8-lambda%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E6%9D%A1%E4%BB%B6%E5%8E%BB%E9%87%8Ddistinct-list%E5%A6%82%E4%BD%95%E5%AE%9E%E7%8E%B0%E6%9D%A1%E4%BB%B6%E5%88%86%E7%BB%84groupby-list/

分類:java
由 Compete Themes 設計的 Author 佈景主題