迭代嵌套映射
我有一个嵌套的hashmap(hashmap中的Hashmap)。
Map<String,Map> test = new HashMap<String,Map>(); Map testMp = new HashMap(); testMp.put("1", "Key1"); testMp.put("2", "Key2"); testMp.put("3", "Key3"); testMp.put("4", "Key4"); testMp.put("5", "Key4"); test.put("One", testMp);
理想情况下,如果我需要在测试图中打印键和值,我会这样做 –
for(Map.Entry<String, Map> t:test.entrySet()) { System.out.println("KEY: " +t.getKey()+ " VALUE:" +t.getValue()); }
但我也想要内部地图的关键和价值。 我想要这样的东西 –
Key of outermap Key of innermap, and its value.
然后做一个嵌套循环:
for(Map.Entry> t:test.entrySet()) { String key = t.getKey(); for (Map.Entry e : t.getValue().entrySet()) System.out.println("OuterKey: " + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue()); }
要么
for(Map.Entry> t:test.entrySet()) { System.out.println(t.getKey()); for (Map.Entry e : t.getValue().entrySet()) System.out.println("KEY: " + e.getKey()+ " VALUE:" +e.getValue()); }
编写一个递归方法,当遇到相应键的条目是一个映射时,它会调用自己。