How to remove an element of a HashMap whilst strea

2019-01-22 18:03发布

问题:

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?

回答1:

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"));


回答2:

I think it's not possible (or deffinitelly shouldn't be done) due to Streams' desire to have Non-iterference, as described here

If you think about streams as your functional programming constructs leaked into Java, then think about the objects that support them as their Functional counterparts and in functional programming you operate on immutable objects

And for the best way to deal with this is to use filter just like you did



回答3:

In case, if you want to remove entire key then use:

myMap.entrySet().removeIf(map -> map.getValue().containsValue("0"));