Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element of a HashMap whilst streaming (lambda)

I have the following situation where I need to remove an element from a stream.

map.entrySet().stream().filter(t -> t.getValue().equals("0")).             forEach(t -> map.remove(t.getKey())); 

in pre Java 8 code one would remove from the iterator - what's the best way to deal with this situation here?

like image 886
Dan Avatar asked May 22 '14 13:05

Dan


People also ask

How do I remove a specific element from a HashMap?

HashMap remove() Method in Java remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map. Parameters: The method takes one parameter key whose mapping is to be removed from the Map.


1 Answers

map.entrySet().removeIf(entry -> entry.getValue().equals("0")); 

You can't do it with streams, but you can do it with the other new methods.

EDIT: even better:

map.values().removeAll(Collections.singleton("0")); 
like image 188
Louis Wasserman Avatar answered Sep 23 '22 01:09

Louis Wasserman