list对象根据对象属性去重

对List中的对象根据某个属性进行去重的情况。例如,我们有一个实体类student,其中包含属性id、name和age,现在我们有一个List<Student>,我们希望根据name属性去除重复的Student对象。

我们可以借助HashSet的特性,来实现根据对象属性去重。我们创建一个HashSet来存放对象的属性值,然后遍历List,根据属性值判断是否添加到HashSet,最后将HashSet转换成List。

public class RemoveDuplicates {

public List<Student> removeDuplicates(List<Student> list) {

Set<String> set = new HashSet<>();

List<Student> result = new ArrayList<>();

for (Student student : list) {

if (set.add(student.getName())) {

result.add(student);

}

}

return result;

}

}

利用Java 8引入的Stream API,结合lambda表达式,更优雅地实现根据对象属性去重。

public class RemoveDuplicates {

public List<Student> removeDuplicates(List<Student> list) {

return list.stream()

.collect(Collectors.toMap(Student::getName, p -> p, (p1, p2) -> p1))

.values()

.stream()

.collect(Collectors.toList());

}

}

相关推荐
会编程的吕洞宾5 小时前
Spring AI 2.0 工具调用实战:让 AI 自动调用你的 Java 方法
java·人工智能·经验分享·后端·spring
斯维赤5 小时前
SELECT * 为什么是覆盖索引的天敌?
java·后端·mysql
stormsha5 小时前
库存 5,10 个并发各买 1 件:为什么最后不剩 -5 件
java·数据库·mysql
RobinXYuan6 小时前
【Java 字节码探秘】02 ClassFile 骨架:十个字段
java·jvm·源码阅读
炸薯条!6 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python
SimonKing7 小时前
又一款数据库同步神器,2.3K Star的dbswitch
java·后端·程序员
CoderYanger7 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
Rain的Java大神之路8 小时前
前端转 Java 全栈:用 AI 两天交付一个能跑的 Demo,踩坑全记录
java·前端·后端
Vex2une8 小时前
把 Windows 装进 U 盘随身携带:Windows To Go 现状与 WinToUSB 制作完全指南
windows·vhdx·windows to go·wintousb·便携windows·系统带进u盘·随身系统
蜡笔小谢18 小时前
DeepSeek Harness Java 实战笔记(五)|插件、MCP 与 Skill
java·笔记·ai·agent·deepseek·harness