I have a final ConcurrentMap in Java and want to filter it's elements without creating a new one.
Question is: can I reference collection (people) from inside the lambda?
final ConcurrentMap<String, String> people = new ConcurrentHashMap<>();
people.put("Sam", "developer");
people.put("Kate", "tester");
people.forEach((name, role) -> {
if (name.length() > 3)
people.remove(name);
});
.keySet()
, .values()
, and .entrySet()
return live views of a map's keys, values and entries respectively. You can remove elements from those collections and the corresponding entries will be removed from the map:
people.keySet().removeIf(name -> name.length() > 3);