- 关于jdk8使用stream去重
1.使用distinct()去重
distinct是stream自带方法,根据hashCode和equals()方法进行去重,会保留第一次出现数据。示例:
list.stream().distinct().collect(Collectors.toList());
2.使用filter
filter是stream自带的筛选方法,需要实现自定义方法;
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
ConcurrentSkipListMap<Object,Boolean> skipListMap = new ConcurrentSkipListMap<>();
return t -> skipListMap.putIfAbsent(keyExtractor.apply(t),Boolean.TRUE);
}
List<entity> list2 = list.stream().filter(distinctByKey((p) -> (p.get属性名称()))).collect(Collectors.toList());
3.使用collectingAndThen。示例:
List<Entity> entityList = collect.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()->new ConcurrentSkipListSet<>(Comparator.comparing(Entity::getAid).thenComparing(Entity::getUid))),ArrayList::new))))