简体   繁体   中英

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?

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 have an ArrayList, multiple removes can be more expensive than taking a copy.

List<Type> list = /* ArrayList */
Set<Type> toRemove = /* HashSet */
List<Type> copy = new ArrayList<Type>(list.size());
for(Type t: list)
  if(!toRemove.contains(t))
    copy.add(t);
list = copy;

Personally I would use a loop. Its likely to be shorter and clearer.

Collection<Type> collection =

for(Iterator<Type> i=collection.iterator(); i.hasNext();)
   if (i.next() is to be removed)
       i.remove();

The reason an Iterator is used explicitly is to use the Iterator.remove() which avoids a ConcurrentModificationException. Another way to avoid it is to use a copy of the collection which might be preferred.

for(Type t : new ArrayList<Type>(collection))
   if (t is to be removed)
       collection.remove(t);

This doesn't perform as well but may perform well enough.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM