向 Map 中的 Set 添加值

Add value to a Set inside a Map

如何向 HashMap 中的 HashSet 添加值?

Map<String, Set<String>> myMap;

答案不短,但简单:

  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);
}