简体   繁体   中英

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 ?

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

遍历所有映射条目,使每个映射条目的值发生变化:

map.forEach((k, v) -> v.remove(productCode)};

使用Java 8和Lambda表达式

map.forEach((key, value) -> value.remove(productCode));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM