Reputation: 2716
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.
Upvotes: 1
Views: 3931
Reputation: 394136
Then do a nested loop :
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());
}
or
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());
}
Upvotes: 3
Reputation: 30849
Write a recursive method which will call itself when it encounters that the entry to corresponding key is a map.
Upvotes: 1