楠笙
返回发现一个list对象根据指定字段去重的代码,因为没太理解,所有就不写文章写在这里记录了
单独的方法
static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
//putIfAbsent方法添加键值对,如果map集合中没有该key对应的值,则直接添加,并返回null,如果已经存在对应的值,则依旧为原来的值。
//如果返回null表示添加数据成功(不重复),不重复(null==null :TRUE)
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}使用
List<PlantEExam> newList = new ArrayList<>();
plantEExams.stream().filter(distinctByKey(PlantEExam::getExamId)) //filter保留true的值
.forEach(newList::add);plantEExams是需要去重的集合
0 位访客