当前位置:网站首页>对象型的集合按某个属性的值进行去重
对象型的集合按某个属性的值进行去重
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
));边栏推荐
- NPM add source and switch source
- Introduction to excellent verilog/fpga open source project (30) - brute force MD5
- PHP和MySQL获取week值不一致的处理
- Sklearn machine learning foundation (linear regression, under fitting, over fitting, ridge regression, model loading and saving)
- Clean the label folder
- Replication of SQL injection vulnerability in the foreground of Pan micro e-cology8
- [use of final keyword]
- Matlab 绘制阴影误差图
- What is the difference between NFT and digital collections?
- Uni app simple mall production
猜你喜欢
随机推荐
数据库操作 题目二
数据库操作技能7
Nuxt - 项目打包部署及上线到服务器流程(SSR 服务端渲染)
对标注文件夹进行清洗
zsh: command not found: nvm
at、crontab
优秀的 Verilog/FPGA开源项目介绍(三十零)- 暴力破解MD5
Web overview and b/s architecture
Espressif plays with the compilation environment
Web概述和B/S架构
Overview of motion recognition evaluation
PAT 甲级 A1034 Head of a Gang
C # use npoi to operate Excel
【无标题】
【LeetCode数据库1050】合作过至少三次的演员和导演(简单题)
CSDN TOP1“一个处女座的程序猿“如何通过写作成为百万粉丝博主?
day06 作业--技能题6
PHP page value transfer
Sklearn machine learning foundation (linear regression, under fitting, over fitting, ridge regression, model loading and saving)
Pytoch learning - from tensor to LR









