If you have an ArrayList, multiple deletions may be more expensive than copying.
List<Type> list = Set<Type> toRemove = 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. It will probably 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 iterator is used explicitly is to use iterator.remove (), which throws a ConcurrentModificationException. Another way to avoid this is to use a copy of the collection, which may be preferable.
for(Type t : new ArrayList<Type>(collection)) if (t is to be removed) collection.remove(t);
This does not work, but may work quite well.
source share