0

I have a many-to-one mapping in java hashmap. I iterate through all the values by using java.util.HashMap.values(). Now if I want to delete a particular value and all the corresponding keys, then what should I do?

Will just using java.util.HashMap.remove(Object key) with one of the keys suffice?

2

1 Answer 1

4

In this example you can remove the values from a map without iteration.

Code

// The test map
final Map<String, String> map = new HashMap<String, String>();
map.put("Key1", "Value");
map.put("Key2", "Value");
map.put("Key3", "Value");

// Remove the map. The collection is necessary to remove all values instead of just one.
map.values().removeAll(Collections.singleton("Value"));

// Print the map to confirm it worked.
System.out.println("Printing Map");
for(final String key : map.keySet()) {
   System.out.println(key + " = " + map.get(key));
}

Output

Printing Map
Sign up to request clarification or add additional context in comments.

2 Comments

Was about to post something very similar. I had two values, x & y. The remove line was map.values().removeIf(y::equals);. Same result.
That is useful if you are using Java 8+

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.