Java collections rely on equals and hashCode methods (the latter are used by HashMap s, HashSet and others).
If you want to use the capabilities of the data structure in Java sets (e.g. removeAll , retainAll , etc.), you need to provide objects with the correct implementations equals and hashCode .
If you cannot change the Item class, you can write a wrapper class with your own equals implementation:
public class ItemWrapper { private final Item item; public ItemWrapper(Item item) { this.item = item; } public Item getItem() { return item; } @Override public boolean equals(Object obj) { return obj instanceof ItemWrapper && item.getId().equals(((ItemWrapper) obj).item.getId()); } @Override public int hashCode() { return item.getId().hashCode(); } }
Create a new ItemWrapper for each original Item , save the ItemWrapper in Java collections and use the necessary methods ( removeAll / retainAll ). Then ItemWrapper over the resulting set and retrieve the Item by calling each ItemWrapper getItem() method.
Another option is to subclass ArrayList , but it seems to be a more confusing solution.
Another option is to not use Java collections for the remove / keep logic, instead implementing them yourself.
source share