向 Map 内的 Set 添加值

Qwe*_*rty -4 java dictionary hashmap set hashset

如何向 HashMap 内的 HashSet 添加值?

Map<String, Set<String>> myMap;
Run Code Online (Sandbox Code Playgroud)

Qwe*_*rty 6

答案并不简短,但很简单:

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

代码:

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

最好这样使用:

// ...

    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);
}
Run Code Online (Sandbox Code Playgroud)