If I am understanding right, the way to do it without making a second collection is like this:
toSet.retainAll(MaterialTypes.IMMOVABLE_TYPES);
for(MaterialTypes mt : fromSet) {
if(!MaterialTypes.IMMOVABLE_TYPES.contains(mt))
toSet.add(mt);
}
fromSet.retainAll(MaterialTypes.IMMOVABLE_TYPES);
Or making explicit use of the Iterator so you can skip one of the calls to retainAll
:
toSet.retainAll(MaterialTypes.IMMOVABLE_TYPES);
for(Iterator<MaterialTypes> it = fromSet.iterator(); it.hasNext();) {
MaterialTypes mt = it.next();
if(!MaterialTypes.IMMOVABLE_TYPES.contains(mt)) {
toSet.add(mt);
it.remove();
}
}
Doing that nets you only two iterations across the Sets and 2 objects created whereas the way you're doing it in the OP uses more like 5 of each. addAll
/retainAll
/removeAll
will use an Iterator internally.
But what you are doing doesn't seem terribly inefficient and I wouldn't personally worry about it. These are actually pretty small objects. If this operation is getting done 10,000 times a second and it's proved to be a bottleneck it's more likely the feature needs to be redesigned so it doesn't use a collection.