Onur Hangul
Onur Hangul

Reputation: 327

Remove one value in hashmap instead of all values and key

I have a hashmap which is Map<String, Set<String>> tasks . Inside the tasks I have some keys and keys have some values, not just a value.

I would like remove a value from hashmap with given key but I also want to keep other values there.

I mean like this release = ["fix bug 1", "fix bugs 2" , "implement feature X"] . now release is key(in String type) and has values(in Set type) "fix bug 1", "fix bugs 2" , "implement feature X" .. I would like to modified release like this :

release = ["implement feature X"]

how can I remove 2 values??? Thanks

Upvotes: 0

Views: 935

Answers (2)

VGR
VGR

Reputation: 44338

Your Map only contains references to Sets, so you can modify the Sets directly and the changes will be seen by the Map.

Which means you can do:

tasks.get("release").removeAll(Arrays.asList("fix bug 1", "fix bug 2"));

Or even:

tasks.get("release").retainAll(Arrays.asList("implement feature X"));

Upvotes: 0

Cimon
Cimon

Reputation: 429

Using the key you can get the Set you want and then remove the value:

map.get("key").removeIf(s -> s.equals("value"));
map.get("key").removeIf(s -> s.equals("value") || s.equals("value1"));

You can do more combinations. There is not need to update the HashMap. it has the reference of Set and whatever happens to Set the HashMap knows it.

Upvotes: 1

Related Questions