1.根据对象的某个属性去重:
网上找的stream流去重方法,可以根据类的某个属性去重,这里记录一下
/**
*只获取重复的数据
* @param keyExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctNotByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) != null;
}
/**
*自定义函数去重(采用 Predicate函数式判断,采用 Function获取比较key)
* 内部维护一个 ConcurrentHashMap,并采用 putIfAbsent特性实现
* @param keyExtractor
* @param <T>
* @return
*/
public 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 testC() {
List<UserAccount> list = new ArrayList<>();
UserAccount a = new UserAccount();
a.setId(57L);
UserAccount b = new UserAccount();
b.setId(57L);
UserAccount c = new UserAccount();
c.setId(56L);
list.add(a);
list.add(b);
list.add(c);
//根据id去重
List<UserAccount> collect = list.stream().filter(distinctByKey(UserAccount::getId)).collect(Collectors.toList());
System.out.println(collect);
System.out.println(collect.size());
}