1

嗨,我想存储嵌套 Map 的键和值,如下所示:

Map<ArrayList <String>, Map<String, Integer>> NestedMap = new HashMap<ArrayList<String>, Map<String, Integer>();

进入另一个变量,让我们说 getKeyFromInsideMap 和 getValueFromInsideMap。因此,对访问感兴趣的是内部 Map String 和 Integer 的值。我如何在代码中做到这一点?

我在论坛中尝试了几个示例,但我不知道语法是什么样的。您能否为此提供一些代码。谢谢!

4

1 回答 1

4

您从嵌套的 Map 中获取值的方式与从未嵌套的 Map 中获取值的方式相同,您只需应用相同的过程两次:

//Java7 Diamond Notation
Map<ArrayList, Map<String, Integer>> nestedMap = new HashMap<>();

//get nested map 
Map<String, Integer> innerMap = nestedMap.get(some_key_value_string);

//now get the Integer value from the innerMap
Integer innerMapValue = innerMap.get(some_key_value_string);

此外,如果您正在寻找特定的键,您可以像这样遍历地图:

Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry)it.next();
    System.out.println("Key: " + pairs.getKey() + " Val: " + pairs.getValue()));
    it.remove(); // avoids a ConcurrentModificationException
}

这将遍历单个映射的所有键和值。

希望这可以帮助。

于 2012-05-15T19:16:11.710 回答