集合数据
List<ThirdStockJdBackupLibraryPo> list = new ArrayList<ThirdStockJdBackupLibraryPo>(){{
add(new ThirdStockJdBackupLibraryPo("123","zs"));
add(new ThirdStockJdBackupLibraryPo("123","ls"));
add(new ThirdStockJdBackupLibraryPo("456","zl"));
}};
需求:根据sku去重。
方式一
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
public static void main(String[] args) {
list.stream().filter(distinctByKey(b -> b.getSku()))
.forEach(b -> System.out.println(b.getSku()+ "," + b.getProductName()));
}
方式二
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
public static void main(String[] args) {
list.parallelStream().filter(distinctByKey1(ThirdStockJdBackupLibraryPo::getSku))
.forEach(System.out::println);
}