答案是重写equals和hashCode后用Set或Stream去重。需根据业务字段重写equals和hashCode方法,再利用HashSet、LinkedHashSet或Stream的distinct实现去除自定义对象重复,注意可变字段可能引发集合行为异常。

在Java中清除集合中的重复自定义对象,关键在于正确重写 equals() 和 hashCode() 方法,并使用合适的集合类型如 HashSet 或 LinkedHashSet 来自动去重。
自定义对象默认使用继承自Object类的 equals() 和 hashCode(),它们基于内存地址判断是否相等,无法识别逻辑上的重复。必须根据业务字段手动重写这两个方法。
例如有一个 Student 类:
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
return age == student.age && Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
Set 接口的实现类不允许重复元素,添加时会自动调用 equals() 和 hashCode() 判断是否重复。
立即学习“Java免费学习笔记(深入)”;
示例代码:
List<Student> list = new ArrayList<>();
list.add(new Student("Alice", 20));
list.add(new Student("Bob", 22));
list.add(new Student("Alice", 20)); // 重复
Set<Student> set = new LinkedHashSet<>(list);
List<Student> noDuplicates = new ArrayList<>(set);
通过 distinct() 方法也能实现去重,底层同样依赖 equals() 和 hashCode()。
List<Student> noDuplicates = list.stream()
.distinct()
.collect(Collectors.toList());
基本上就这些。只要保证 equals() 和 hashCode() 正确,去重就不难。注意:如果对象字段会变,不建议用作 HashMap 的 key 或放入 Set,否则可能引发不可预期的问题。
以上就是Java中如何清除集合中的重复自定义对象的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号