Java8 stream 实现对象List根据对象某一指定字段进行去重操作

Java8 stream 可简洁实现对象List根据对象的某一字段进行去重。

实现代码如下:

根据去重场景修改代码中的对象及去重字段即可。

//根据Student对象的age进行去重
studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student :: getAge))), ArrayList::new));

注:若存在两个 age 相同的student,其他数据不同,留下的数据是靠前的数据,去除的是靠后的数据。

例如:

List<Student> studentList = new ArrayList<>();
studentList.add(new Student("1","哈哈","18"));
studentList.add(new Student("2","哼哼","18"));
studentList = studentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Student :: getAge))), ArrayList::new));

根据 age 去重后结果:学生“哈哈”被保留,学生“哼哼”被去除。

查看更多常用流式操作 Java8 stream 常用操作汇总

  • 7
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值