迭代嵌套映射

时间:2014-08-22 21:08:07

标签: java

我有一个嵌套的hashmap(hashmap中的Hashmap)。

Map<String,Map<String,String>> test = new HashMap<String,Map<String,String>>();
    Map<String,String> testMp = new HashMap<String,String>();
    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<String,String>> t:test.entrySet()) {
            System.out.println("KEY: " +t.getKey()+ " VALUE:" +t.getValue());
}

但我也想要内部地图的关键和价值。我想要这样的东西 -

Key of outermap
    Key of innermap, and its value.

2 个答案:

答案 0 :(得分:3)

然后做一个嵌套循环:

for(Map.Entry<String, Map<String,String>> t:test.entrySet()) {
   String key = t.getKey();
   for (Map.Entry<String,String> e : t.getValue().entrySet())
     System.out.println("OuterKey: " + key + " InnerKey: " + e.getKey()+ " VALUE:" +e.getValue());
}

for(Map.Entry<String, Map<String,String>> t:test.entrySet()) {
   System.out.println(t.getKey());
   for (Map.Entry<String,String> e : t.getValue().entrySet())
     System.out.println("KEY: " + e.getKey()+ " VALUE:" +e.getValue());
}

答案 1 :(得分:1)

编写一个递归方法,当它遇到相应键的条目是地图时会调用它自己。