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

原文地址:https://www.cnblogs.com/june0816/p/14246247.html