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());

}

}

相关推荐
.格子衫.3 小时前
Spring Boot 原理篇
java·spring boot·后端
多云几多3 小时前
Yudao单体项目 springboot Admin安全验证开启
java·spring boot·spring·springbootadmin
Jabes.yang6 小时前
Java求职面试实战:从Spring Boot到微服务架构的技术探讨
java·数据库·spring boot·微服务·面试·消息队列·互联网大厂
聪明的笨猪猪6 小时前
Java Redis “高可用 — 主从复制”面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试
兮动人6 小时前
Spring Bean耗时分析工具
java·后端·spring·bean耗时分析工具
MESSIR226 小时前
Spring IOC(控制反转)中常用注解
java·spring
摇滚侠6 小时前
Spring Boot 3零基础教程,Demo小结,笔记04
java·spring boot·笔记
笨手笨脚の7 小时前
设计模式-迭代器模式
java·设计模式·迭代器模式·行为型设计模式
spencer_tseng8 小时前
Eclipse 4.7 ADT (Android Development Tools For Eclipse)
android·java·eclipse
聪明的笨猪猪8 小时前
Java Spring “AOP” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试