Java8集合中的对象根据指定字段去重,并根据条件获取指定去重后的对象

文章介绍了在Java8中对集合对象进行去重的三种方法:使用distinct()方法,利用collectingAndThen()结合toCollection创建TreeSet,以及通过Collectors.toMap()。对于多个字段的去重,可以通过自定义比较器实现。同时,展示了如何根据特定条件选择去重后的对象。

Java8集合中的对象根据指定字段去重,并根据条件获取指定去重后的对象

一、distinct去重

 List uniqueList = list.stream().distinct().collect(Collectors.toList());

二、collectingAndThen去重

一个字段:

ArrayList<PaperRecord> paperRecordList = list.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(PaperRecord::getUserId))), ArrayList::new)
            );

多个字段:

ArrayList<PaperRecord> paperRecordList = list.stream().collect(
                    Collectors.collectingAndThen(
                            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(item->item.getUserId()+"_"+item.getPassStatus()))), ArrayList::new)
            );

三、Collectors.toMap去重

去重取旧对象:

List<PaperRecord> paperRecordList = new ArrayList<>(list.stream()
                    .collect(Collectors.toMap(item -> item.getUserId(), Function.identity(), (oldValue, newValue) -> oldValue))
                    .values());

去重根据条件取对象:

List<PaperRecord> paperRecordList = new ArrayList<>(list.stream()
                    .collect(Collectors.toMap(item -> item.getUserId(), Function.identity(), (oldValue, newValue) -> oldValue.getPassStatus() ? oldValue : newValue))
                    .values());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值