I want to compute differences between collections. When using CollectionUtils.subtract() for custom comparison I need to override the object's equals() method. But what if I need to compare collections of objects of the same type but different comparison criterion? What about the Comparator interface, it seems perfectly suited here? AFAIK Comparator is mainly used for sorting. Isn't there a method that uses Comparators for subtracting?
static <Type> Collection<Type> subtract(Collection<Type> a, Collection<Type> b, Comparator<Type> c) {
Set<Type> subtrahend = new TreeSet<Type>(c);
subtrahend.addAll(b);
Collection<Type> result = new ArrayList<Type>();
for (Type item: a) {
if (!subtrahend.contains(item)) result.add(item);
}
return result;
}
The subtrahent
tree-set is not necessary, but will improve performance for large b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With