英文:
Remove one value in hashmap instead of all values and key
问题
我有一个哈希映射,其结构为 Map<String, Set<String>> tasks
。在 tasks 中,我有一些键,而这些键又包含了一些值,不仅仅是一个值。
我想要从哈希映射中删除具有给定键的某个值,但同时保留其他值。
我的意思是像这样 release = ["fix bug 1", "fix bugs 2" , "implement feature X"]
。现在 release
是一个键(String 类型),包含了值(Set<String> 类型)"fix bug 1", "fix bugs 2" , "implement feature X"
。我想要修改 release
如下:
release = ["implement feature X"]
我该如何删除两个值?谢谢
英文:
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<String> 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
答案1
得分: 1
利用这个键,你可以获取到想要的集合,然后移除特定的值:
map.get("key").removeIf(s -> s.equals("value"));
map.get("key").removeIf(s -> s.equals("value") || s.equals("value1"));
你可以进行更多的组合。不需要更新 HashMap,它持有集合的引用,无论对集合做了什么操作,HashMap 都会知道。
英文:
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.
答案2
得分: 0
你的地图仅包含对集合的引用,因此你可以直接修改集合,地图会反映出这些更改。
这意味着你可以这样做:
tasks.get("release").removeAll(Arrays.asList("fix bug 1", "fix bug 2"));
甚至可以这样做:
tasks.get("release").retainAll(Arrays.asList("implement feature X"));
英文:
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"));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论