java hashset 多字段去重需要自定义对象并重写 equals 和 hashcode 方法,或者使用支持比较器的 treeset。核心做法是将多个业务字段组合成唯一的哈希值,确保逻辑上相同的对象在集合中只保留一份。

如何重写 equals 和 hashCode 实现多字段去重
通过重写这两个方法,可以让 HashSet 根据对象的属性内容而非内存地址来判断重复。具体做法是在 hashCode 中结合所有关键字段计算哈希值,在 equals 中逐一比对这些字段的值。

import java.util.HashSet;
import java.util.Objects;
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof User)) return false;
User user = (User) o;
return age == user.age && Objects.equals(name, user.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public static void main(String[] args) {
HashSet<user> set = new HashSet();
set.add(new User("Alice", 30));
set.add(new User("Alice", 30)); // 重复
set.add(new User("Bob", 25));
System.out.println(set.size()); // 输出 2
}
}</user>
如何使用 Comparator 配合 TreeSet 进行多字段排序去重
如果需要在去重的同时进行排序,可以使用 TreeSet 并传入一个 Comparator。该比较器需定义多字段的优先级顺序,当所有比较字段相等时返回 0,从而判定为重复元素。
FilePond 是一个 JavaScript 文件上传库,支持通过拖拽、粘贴和 API 方式处理文件、目录、URL 和 Data URI。它包含内置的图像优化功能、异步分块上传功能,并提供了适用于 React、Vue、Angular 和 Svelte 的适配器。

import java.util.Comparator;
import java.util.TreeSet;
public class Product {
private String category;
private double price;
public Product(String category, double price) {
this.category = category;
this.price = price;
}
public static void main(String[] args) {
Comparator<product> comp = Comparator
.comparing(Product::getCategory)
.thenComparingDouble(Product::getPrice);
TreeSet<product> set = new TreeSet(comp);
set.add(new Product("A", 10.0));
set.add(new Product("A", 10.0)); // 重复
set.add(new Product("B", 20.0));
System.out.println(set.size()); // 输出 2
}
public String getCategory() { return category; }
public double getPrice() { return price; }
}</product></product>
当 equals 返回 true 但 hashCode 不同时会发生什么
如果 equals 返回 true 但 hashCode 不同,HashSet 的行为取决于具体的实现细节,但在标准规范中这违反了契约。通常 HashSet 先检查哈希桶,若哈希不同则直接存入新桶,导致逻辑重复对象被同时保留。这会破坏集合的唯一性保证。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










