登录
首页 >  文章 >  java教程

Java去除集合重复自定义对象方法

时间:2025-12-10 08:26:30 153浏览 收藏

推广推荐
免费电影APP ➜
支持 PC / 移动端,安全直达

文章不知道大家是否熟悉?今天我将给大家介绍《Java如何去除集合重复自定义对象》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

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

Java中如何清除集合中的重复自定义对象

在Java中清除集合中的重复自定义对象,关键在于正确重写 equals()hashCode() 方法,并使用合适的集合类型如 HashSetLinkedHashSet 来自动去重。

1. 重写 equals() 和 hashCode()

自定义对象默认使用继承自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);
    }
}

2. 使用 Set 集合去重

Set 接口的实现类不允许重复元素,添加时会自动调用 equals()hashCode() 判断是否重复。

  • 使用 HashSet:无序去重
  • 使用 LinkedHashSet:保持插入顺序

示例代码:

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

3. 使用 Java 8 Stream 去重

通过 distinct() 方法也能实现去重,底层同样依赖 equals()hashCode()

List<Student> noDuplicates = list.stream()
                                  .distinct()
                                  .collect(Collectors.toList());

基本上就这些。只要保证 equals()hashCode() 正确,去重就不难。注意:如果对象字段会变,不建议用作 HashMap 的 key 或放入 Set,否则可能引发不可预期的问题。

以上就是《Java去除集合重复自定义对象方法》的详细内容,更多关于的资料请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>