通过Stream.filter不同属性来过滤重复
/**
* 通过对象属性去重
*
* @param keyExtractor
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
根据属性去重,并且进行信息整合
/**
* 通过对象属性去重,并对相同Key的对象执行操作,适合两个list相同属性并集
*
* @param keyExtractor
* @param thenFunction
* @param <T>
* @return
*/
public static <T> Predicate<T> distinctAndThen(Function<? super T, Object> keyExtractor,
BiConsumer<T, T> thenFunction) {
Map<Object, T> map = new ConcurrentHashMap<>(10);
return t -> {
if (map.containsKey(keyExtractor.apply(t))) {
thenFunction.accept(t, map.get(keyExtractor.apply(t)));
return false;
} else {
map.put(keyExtractor.apply(t), t);
return true;
}
};
}