user3182266 user3182266 - 10 days ago 6
Android Question

Java: How to properly remove a value from a HashMap NOT based on the key

I have a

Singleton
class that inside has a HashMap. The HashMap is made of
String
and
Set<String>
:

private Map<String, Set<String>> mMap = new HashMap<>();


What I want to achieve?

Remove a given item from all the
Set
values inside the
Map
. For example:

mMap.put(keyName, new HashSet<String>())
....
mViewsSwipeStates.get(keyName).add("1");
mViewsSwipeStates.get(keyName).add("2");
mViewsSwipeStates.get(keyName).add("3");
....
//Remove an item from the set
mMap.values().remove("3"); //Does not work


What is the correct way to remove an item from inside the
Set
?

Answer

I'm assuming you want to remove productCode from all the values of the Map (and not just from the value of a specific key).

You have to iterate over all the values of the Map, and remove from each of them the required element :

mMap.values().forEach(v->v.remove(productCode));

This code assumes there are no null values in the Map.

EDIT :

In Java 7 you can write:

for (Set<String> value : mMap.values()) {
    value.remove(productCode);
}