Getting value from Nested HashMap into another Map

自古美人都是妖i 提交于 2020-01-06 03:14:08

问题


Hi, I wanted to store key and value of a nested Map that looks like this:

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

into another variable let say getKeyFromInsideMap and getValueFromInsideMap. So it would be the values of the inside Map String and Integer that am interested in accessing. How do I this in a code?

I tried several examples here in the forum but I don't know how the syntax would look like. Could you please provide some code for this. Thank you!


回答1:


You get the values from the nested by Map the same way as you get them from an unnested Map, you just have to apply the same process twice:

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

Also if you are looking for a specific key, you can iterate over the map like so:

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
}

this will iterate over all of the keys and value of a single map.

Hope this helps.



来源:https://stackoverflow.com/questions/10607287/getting-value-from-nested-hashmap-into-another-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!