吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1014|回复: 4
收起左侧

[学习记录] java学习之list去重

[复制链接]
moqidongli 发表于 2022-3-16 13:24

1、使用toCollection和TreeSet去重

TreeSet内部使用的是TreeMap,使用指定Comparator比较元素,如果元素相同,则新元素代替旧元素。

List<TalentPlanStudentEntity> studentList = relatePlanStudentList.stream()
                    .collect(Collectors.collectingAndThen(Collectors.toCollection(
                            () -> new TreeSet<>(Comparator.comparing(TalentPlanStudentEntity::getUserId))), ArrayList::new));

2、使用Collectors.toMap去重

Collectors.toMap需要使用三个参数的版本,前两个参数一个是keyMapper函数一个是valueMapper函数的,第三个参数BinaryOperator函数接口。BinaryOperator函数接收两个参数,一个oldValue,一个newValue。用于当key重复时的数据处理

List<TalentPlanStudentEntity> studentList = new ArrayList<>(relatePlanStudentList.stream()
                    .collect(Collectors.toMap(TalentPlanStudentEntity::getUserId, Function.identity(), (oldValue, newValue) -> oldValue))
                    .values());

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

lf19891031 发表于 2022-3-16 15:45
学到了 谢谢
Caraciold_Jr 发表于 2022-3-16 16:50
wlhy 发表于 2022-3-16 18:08
 楼主| moqidongli 发表于 2022-3-17 09:09
wlhy 发表于 2022-3-16 18:08
一般不是转成LinkedHashSet就可以吗?

去重的方式很多,分享下我习惯用的。大佬可以分享下代码供学习一下
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 警告:本版块禁止回复与主题无关非技术内容,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-4-29 04:19

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表