【问题标题】:Add value to a Set inside a Map向 Map 内的 Set 添加值
【发布时间】:2015-06-28 19:21:40
【问题描述】:

如何向 HashMap 中的 HashSet 添加值?

Map<String, Set<String>> myMap;

【问题讨论】:

  • 你能详细说明I haven't found an answer targeting the general concept.是什么意思
  • 我对它投了反对票,因为在您发表评论后Try searching for an answer here on SO. The answers are made to fit the exact problems OPs have faced。我做了完全相同的事情,并找到了一个完全回答您的问题的答案:stackoverflow.com/questions/15797446/…。因此,当您说您没有找到满足您要求的答案时,您需要详细说明与其他答案相比它不满足的要求。
  • 这个问题是discussed on MetaSO

标签: java dictionary hashmap set hashset


【解决方案1】:

答案并不简短,而是简单:

  1. get集合
  2. 确保它不是 null
    如果它是空的 put 首先在地图中。
  3. 更改集合
    对集合的更改会自动反映在地图中。

文件代码:

Set<String> theSet = myMap.get(aKey);
if (theSet == null) {
    theSet = new HashSet<String>();
    myMap.put(aKey, theSet);
}
theSet.add(value);

最好这样使用:

// ...

    Map<String, Set<String>> myMap = new HashMap<String, Set<String>>();
    addValue("myValue", "myKey", myMap);

// ...


private void addValue(String value, String key, Map<String, Set<String>> map) {
    Set<String> set = map.get(key);
    if (set == null) {
        set = new HashSet<String>();
        map.put(key, set);
    }
    set.add(value);
}

【讨论】:

  • 只有当它为空时,您才需要将它放回原处。否则,put 是多余的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-01-23
  • 1970-01-01
  • 2016-01-08
  • 2021-11-05
  • 2020-10-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多