如何将值放在Map中的Map中

时间:2013-06-17 20:43:14

标签: java map

如何在此地图中添加值?

public static Map<String, TreeMap<String, SomeClass>> myMap=Collections.synchronizedMap(new TreeMap<String, TreeMap<String,SomeClass>>());

3 个答案:

答案 0 :(得分:1)

首先,您需要确保“内部地图”存在,然后您可以将值放入其中:

String outerKey = "exampleKey1";
String innerKey = "exampleKey2";
SomeClass innerValue = new SomeClass();

TreeMap<String, SomeClass> innerMap = myMap.get(outerKey);
if (innerMap == null) {
  innerMap = Collections.synchronizedMap(new TreeMap<String, SomeClass>());
  myMap.put(outerKey, innerMap);
}
innerMap.put(innerKey, innerValue);

您还应该考虑将类型更改为:

public static Map<String, SortedMap<String, SomeClass>> myMap = ...
//                        ^^^^^^^^^

或仅Map,具体取决于您是否需要已排序的属性。

答案 1 :(得分:1)

TreeMap<String, SomeClass> map = myMap.get(key1)
if(map == null) {
  map = Collections.synchronizedMap(new TreeMap<String, SomeClass>());
  myMap.put(key1, map);
}
map.put(key2, value);

答案 2 :(得分:0)

TreeMap<String, SomeClass> value = new TreeMap<String, SomeClass>();
myMap.put("key", value);