从哈希映射中删除一个值,而不是所有值和键。

huangapple go评论75阅读模式
英文:

Remove one value in hashmap instead of all values and key

问题

我有一个哈希映射,其结构为 Map<String, Set<String>> tasks。在 tasks 中,我有一些键,而这些键又包含了一些值,不仅仅是一个值。

我想要从哈希映射中删除具有给定键的某个值,但同时保留其他值。

我的意思是像这样 release = [&quot;fix bug 1&quot;, &quot;fix bugs 2&quot; , &quot;implement feature X&quot;]。现在 release 是一个键(String 类型),包含了值(Set<String> 类型)&quot;fix bug 1&quot;, &quot;fix bugs 2&quot; , &quot;implement feature X&quot;。我想要修改 release 如下:

release = [&quot;implement feature X&quot;]

我该如何删除两个值?谢谢

英文:

I have a hashmap which is Map&lt;String, Set&lt;String&gt;&gt; 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 = [&quot;fix bug 1&quot;, &quot;fix bugs 2&quot; , &quot;implement feature X&quot;] . now release is key(in String type) and has values(in Set<String> type) &quot;fix bug 1&quot;, &quot;fix bugs 2&quot; , &quot;implement feature X&quot; .. I would like to modified release like this :

release = [&quot;implement feature X&quot;]

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(&quot;key&quot;).removeIf(s -&gt; s.equals(&quot;value&quot;));
map.get(&quot;key&quot;).removeIf(s -&gt; s.equals(&quot;value&quot;) || s.equals(&quot;value1&quot;));

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(&quot;release&quot;).removeAll(Arrays.asList(&quot;fix bug 1&quot;, &quot;fix bug 2&quot;));

Or even:

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

huangapple
  • 本文由 发表于 2020年10月14日 03:00:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64341567.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定