I have a method that has to remove any element listed in a (small) Set<K> keysToRemove
from some (potentially large) Map<K,V> from
. But removeAll()
doesn't do, as I need to return all keys that were actually removed, since the map might or might not contain keys that require removal.
Old-school code is straight forward:
public Set<K> removeEntries(Map<K, V> from) {
Set<K> fromKeys = from.keySet();
Set<K> removedKeys = new HashSet<>();
for (K keyToRemove : keysToRemove) {
if (fromKeys.contains(keyToRemove)) {
fromKeys.remove(keyToRemove);
removedKeys.add(keyToRemove);
}
}
return removedKeys;
}
The same, written using streams:
Set<K> fromKeys = from.keySet();
return keysToRemove.stream()
.filter(fromKeys::contains)
.map(k -> {
fromKeys.remove(k);
return k;
})
.collect(Collectors.toSet());
I find that a bit more concise, but I also find that lambda too clunky.
Any suggestions how to achieve the same result in less clumsy ways?