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 分钟前
C# 常量与变量
java·算法·c#
Java技术小馆18 分钟前
GitDiagram如何让你的GitHub项目可视化
java·后端·面试
Codebee35 分钟前
“自举开发“范式:OneCode如何用低代码重构自身工具链
java·人工智能·架构
程序无bug1 小时前
手写Spring框架
java·后端
程序无bug1 小时前
Spring 面向切面编程AOP 详细讲解
java·前端
全干engineer1 小时前
Spring Boot 实现主表+明细表 Excel 导出(EasyPOI 实战)
java·spring boot·后端·excel·easypoi·excel导出
Fireworkitte1 小时前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
GodKeyNet2 小时前
设计模式-责任链模式
java·设计模式·责任链模式
Paper_Love2 小时前
x86-64_windows交叉编译arm_linux程序
arm开发·windows
a_Dragon12 小时前
Spring Boot多环境开发-Profiles
java·spring boot·后端·intellij-idea