【问题标题】:List within HashMap remove one valueHashMap 中的列表删除一个值
【发布时间】:2018-03-28 05:24:28
【问题描述】:

我在 hashmap 中有一个列表,

HashMap<String, List<String>>)

所以一个键有多个值,如何只删除一个特定键的一个值..

通常我们直接删除值..

hashmap.remove(key);

删除值..但我需要从值列表中删除一个值..

List<String> list = Arrays.asList("one","two","three");
HashMap<String, List<String>> hm = new HashMap<String, List<String>> ();

hm.add("1",list);

我不确定如何从键“1”的列表中单独删除值“two”..

【问题讨论】:

  • 你需要获取列表并调用remove就可以了

标签: java list hashmap


【解决方案1】:

您通过get 获取值并使用removeList 中删除相关元素:

hm.get("1").remove("two");

当然你必须保护自己免受get返回null的情况:

hm.computeIfPresent("1",(k,v)->{v.remove("two");return v;});

类似于:

if (hm.get("1") != null) {
    hm.get("1").remove("two");
}

另请注意,您放入Map(由Arrays.asList() 返回)中的List 具有固定大小,这意味着您无法从中删除元素。调用remove 将抛出UnsupportedOperationException。您可以改用List&lt;String&gt; list = new ArrayList&lt;&gt;(Arrays.asList("one","two","three")); 来修复它。

【讨论】:

  • @mannedear computeIfPresent 需要BiFunction&lt;? super K, ? super V, ? extends V&gt;,这是一个接受两个参数(在本例中为键和值)并返回一个值的函数。 return v; 返回值。
【解决方案2】:

在从中删除元素之前,您需要先获取内部列表。

应该这样做:

hm.get("1").remove("two");

【讨论】:

  • 这里key这个词是什么意思,是指HashMap&lt;key, value&gt;key吗?
  • 他在他的例子中使用了它。为了更好地理解,我一直这样。它是应该被删除的列表条目。
  • 所以您现在通过将单词 key 替换为 "two" 来编辑您的答案,现在这很有意义。
  • 如果您查看他的示例,您会清楚地看到该键不可能是 hashmap 的键,因为键是“1”。而我的第一个get也有“1”hm.add("1",list);
猜你喜欢
  • 1970-01-01
  • 2016-08-28
  • 1970-01-01
  • 2021-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
相关资源
最近更新 更多