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

在Java中清除集合中的重复自定义对象,关键在于正确重写 equals() 和 hashCode() 方法,并使用合适的集合类型如 HashSet 或 LinkedHashSet 来自动去重。
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() 判断是否重复。
立即学习“Java免费学习笔记(深入)”;
彩葫芦
用AI生成故事漫画、科普绘本、小说插画,加入彩葫芦绘画社区,一起释放创造力!
111 查看详情
使用 HashSet:无序去重 使用 LinkedHashSet:保持插入顺序
示例代码:
List list = new ArrayList();list.add(new Student("Alice", 20));list.add(new Student("Bob", 22));list.add(new Student("Alice", 20)); // 重复Set set = new LinkedHashSet(list);List noDuplicates = new ArrayList(set);
3. 使用 Java 8 Stream 去重
通过 distinct() 方法也能实现去重,底层同样依赖 equals() 和 hashCode()。
List noDuplicates = list.stream() .distinct() .collect(Collectors.toList());
基本上就这些。只要保证 equals() 和 hashCode() 正确,去重就不难。注意:如果对象字段会变,不建议用作 HashMap 的 key 或放入 Set,否则可能引发不可预期的问题。
以上就是Java中如何清除集合中的重复自定义对象的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/767740.html
微信扫一扫
支付宝扫一扫