Removing duplicates without overriding hashCode ()

For enterprise reasons, I cannot override hashCode, and I have to use Java 6 (but I can use guava)

What is the best bests / simpleest / quickest / most efficient / [insert indetermine adjective to best] mechanism for removing duplicate beans from a Java collection?

A duplicate is defined by a subset of getters that return the same value, for example.

pojoA.getVal() == pojoB.getVal() && pojoA.getOtherVal() == pojoB.getOtherVal()
+4
source share
2 answers

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 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<Wrapper>:

Set<Wrapper> set = new HashSet<>();
for (ActualData item : listWithDuplicates) {
    if (!set.add(new Wrapper(item))) {
        System.out.println("Item "+item+" was a duplicate");
    }
}
+10

new TreeSet<Pojo> (comparator) , ( , , ) , - .

if (pojoA.getVal() != pojoB.getVal())
  return Integer.compare(pojoA.getVal(), pojoB.getVal());
if (pojoA.getOtherVal() != pojoB.getOtherVal())
  return Integer.compare(pojoA.getOtherVal(), pojoB.getOtherVal());
return 0;

, HashSet, - , @dasblikenlight .

+3

Source: https://habr.com/ru/post/1620156/


All Articles