Reputation: 3761
I've one Map<Long, String>
& one Set<Long>
.
Say,
Map<Long, String> mapA
Set<Long> setB
I want to remove those entries from mapA
, whose keys are not in setB
.
Also I want to print log for all the entries which have been removed from mapA
.
Currently I'm using iterator.
for (Iterator<Map.Entry<Long, String>> iterator = mapA.entrySet().iterator();
iterator.hasNext(); ) {
Map.Entry<Long, String> entry = iterator.next();
if (!setB.contains(entry.getKey())) {
LOGGER.error(entry.getKey() + " does not exist");
// Removing from map.
iterator.remove();
}
}
How can I do it more concisely using Java8?
Upvotes: 0
Views: 214
Reputation: 59970
You can use streams like this;
mapA.entrySet().removeIf(e -> {
if(setB.contains(e.getKey())){
return true;
}
LOGGER.error(e.getKey() + " does not exist");
return false;
});
Or mush better you can call the keySet, if you don't need the values:
mapA.keySet().removeIf(k -> {
if (setB.contains(k)) {
return true;
}
LOGGER.error(k + " does not exist");
return false;
});
Upvotes: 2