List集合根据对象某个属性去重

今天在工作中用到了根据集合中对象的某个属性来去重,找了很多方法,都比较麻烦,最后发现了一个巨简单的方法

public class Test {
    public static void main(String[] args) {
        List<User> list = new Lists.newArrayList();
        list.add(new user(1,"张三","上海"));
        list.add(new user(2,"李四","北京"));
        list.add(new user(3,"王五","济南"));
        list.add(new user(4,"李四","北京"));

        // 根据list中的City城市来去重
        newList = list.stream().filter(distinctByKey(User::getCity)).collect(Collectors.toList());
    }
    
    private static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

最主要的是 distinctByKey 方法,实现了根据集合某个属性去重,在结合Java8的流中的筛选 filter ,最终实现了最简单的List集合根据对象某个属性去重

 

原文链接:https://blog.csdn.net/weixin_45768481/article/details/106268221

posted @ 2020-12-11 20:07  uzxin  阅读(3517)  评论(0编辑  收藏  举报