Java stream根据对象某个字段过滤重复数据:distinctByKey

一、原生的distinct()不支持按照列表里的对象某个属性去重

 

二、对某个字段过滤重复数据:使用HashMap

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;
    }
list.stream().filter(distinctByKey(User::getId)).collect(Collectors.toList());

 

 

 

参考:

https://www.cnblogs.com/unknows/p/13534953.html

 

posted @ 2021-01-19 15:06  牧云文仔  阅读(16866)  评论(0编辑  收藏  举报