当前位置:网站首页>对象型的集合按某个属性的值进行去重
对象型的集合按某个属性的值进行去重
2022-07-26 09:05:00 【Hejjon】
直接上代码吧, 哈哈哈
public class RemoveDuplicateTest {
public static void main(String[] args) {
List<User> userList = new ArrayList<>();
userList.add(new User("zs", 19, 80.0));
userList.add(new User("zs", 18, 76.0));
userList.add(new User("lisi", 20, 70.0));
userList.add(new User("zs", 21, 90.0));
userList.add(new User("lisi", 22, 60.0));
userList.add(new User("wangwu", 18, 86.0));
int num = 0;
for (User user : userList) {
System.out.println(user);
num++;
}
System.out.println("去重前数量: " + num);
// 按name属性去重
// 常规写法
Set<String> nameSet = new HashSet<>();
List<User> resList = new ArrayList<>();
for (User user : userList) {
if (!nameSet.contains(user.getName())) {
resList.add(user);
}
nameSet.add(user.getName());
}
int num2 = 0;
for (User user : resList) {
System.out.println(user);
num2++;
}
System.out.println("去重后数量: " + num2);
// 使用jdk8新特性写法
List<User> resList2 = userList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))), ArrayList::new
));
for (User user : resList2) {
System.out.println(user);
}
}
}重点是jdk8新特性的写法
// 使用jdk8新特性写法
List<User> resList2 = userList.stream().collect(Collectors.collectingAndThen(
Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))), ArrayList::new
));边栏推荐
- Two tips for pycharm to open multiple projects
- Nuxt - Project packaging deployment and online to server process (SSR server rendering)
- Overview of motion recognition evaluation
- 多项式开根
- Review notes of Microcomputer Principles -- zoufengxing
- Canal 的学习笔记
- Database operation topic 2
- 围棋智能机器人阿法狗,阿尔法狗机器人围棋
- Codeworks DP collection
- CF1481C Fence Painting
猜你喜欢
随机推荐
Day 6 summary & database operation
数据库操作 技能6
第6天总结&数据库作业
Elastic APM安装和使用
NPM add source and switch source
分布式跟踪系统选型与实践
Error: Cannot find module ‘umi‘ 问题处理
day06 作业--增删改查
[leetcode database 1050] actors and directors who have cooperated at least three times (simple question)
Day06 homework - skill question 6
HBuilderX 运行微信开发者工具 “Fail to open IDE“报错解决
深度学习常用激活函数总结
2022年上海市安全员C证考试试题及模拟考试
垂直搜索
Clean the label folder
Form form
Web概述和B/S架构
zsh: command not found: nvm
Media at home and abroad publicize that we should strictly grasp the content
QtCreator报错:You need to set an executable in the custom run configuration.









