繁体   English   中英

遍历嵌套地图

[英]Iterate through nested map

我有一个嵌套的哈希图(哈希图中的哈希图)。

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.

然后做一个嵌套循环:

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());
}

编写一个递归方法,当遇到相应键的条目是映射时将调用自身。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM