将感兴趣的对象包装到您自己的类中,并覆盖它hashCode
/ equals
以关注特定的属性子集.创建一个包装器的哈希集,然后从集合中获取对象以获得无重复的子集.
这是一个例子:
class ActualData { public String getAttr1(); public String getAttr2(); public String getAttr3(); public String getAttr4(); }
假设您要关注属性1,2和4.然后您可以创建一个这样的包装器:
class Wrapper { private final ActualData data; public ActualData getData() { return data; } private final int hash; public Wrapper(ActualData data) { this.data = data; this.has = ... // Compute hash based on data's attr1, 2, and 4 } @Override public int hashCode() { return hashCode; } @Override public boolean equals(Object obj) { if (!(obj instanceof Wrapper)) return false; Wrapper other = (Wrapper)obj; return data.getAttr1().equals(other.getAttr1()) && data.getAttr2().equals(other.getAttr2()) && data.getAttr4().equals(other.getAttr4()); } }
现在你可以做一个HashSet
:
Setset = new HashSet<>(); for (ActualData item : listWithDuplicates) { if (!set.add(new Wrapper(item))) { System.out.println("Item "+item+" was a duplicate"); } }