迭代嵌套映射 [英] Iterate through nested map

查看:218
本文介绍了迭代嵌套映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a nested hashmap (Hashmap inside a 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);

理想情况下,如果我需要打印测试图中的键和值,我会这样做 -

Ideally if I need to print the key and the values in the test map, I'd do this -

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

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

But I want the key and the value of the inner map as well. I want something like this -

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

这篇关于迭代嵌套映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆