This is very easy if I just want to base this on absolute equality. I'd just do:
collectionA.removeAll(collectionB).
However, let's say I have this object:
class Item {
private String color;
private String name;
private String type;
}
And two collections...
List<Item> items1, List<item> items2.
...but I just want to remove everything from item1 that has the same name and type as something in item2.
Note that I can't subclass or define equals, hashcode for this class.
I'd want this to be the same complexity of the existing collections.removeAll method.
The best solution I can think of would be something like:
class SimpleItem {
String name;
String type;
Item item;
public SimpleItem(Item item) {
this.name = item.getName();
this.type = item.getType();
}
@Override
public boolean equals(Object obj) {
...
}
@Override
public int hashCode() {
...
}
}
Set<SimpleItem> simpleItems1 = ...;
for (Item item : items1) {
simpleItems1.add(new SimpleItem(item));
}
Set<SimpleItem> simpleItems2 = ...;
for (Item item : items2) {
simpleItems2.add(new SimpleItem(item));
}
simpleItems1.removeAll(simpleItems2);
Set<Item> items = ...;
for (SimpleItem simpleItem : simpleItems) {
items.add(simpleItem.item);
}
...but that is insanely verbose. It's Java 8. What clever solution am I missing?