Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract collections with Comparator interface instead of overriding equals

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?

like image 737
mamuesstack Avatar asked Sep 08 '11 12:09

mamuesstack


1 Answers

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.

like image 109
Cephalopod Avatar answered Sep 24 '22 07:09

Cephalopod