BobRoss BobRoss - 1 year ago 237
Java Question

Map inside map iteration

private Map<String, Map<String, String>> messagesByFactTypeAndCategory;

public void setMessagesByFactTypeAndCategory(Map<String, Map<String, String>> messagesByFactTypeAndCategory) {
this.messagesByFactTypeAndCategory = messagesByFactTypeAndCategory;

public Map<String, Map<String, String>> getMessagesByFactTypeAndCategory() {
if (messagesByFactTypeAndCategory == null) {
return Maps.newHashMap();
return messagesByFactTypeAndCategory;

This code is in it's own class. I'm trying but unable to get the data inside this to display inside my main. I've tried quite a number of solutions other user's have mentioned in online examples but can't correctly apply them to my problem. Any help is appreciated! Below is what I the most current solution I have tried to get some type of output, yet it is not displaying.

Map<String, Map<String, String>> newMap = executionResult.getMessagesByFactTypeAndCategory();
Set set = newMap.entrySet();
Iterator iterator = set.iterator();
while(iterator.hasNext()) {
Map.Entry mentry = (Map.Entry);
System.out.print("key is: "+ mentry.getKey() + " & Value is: ");

Answer Source

If you just need to traverse all entries of both maps, you can do it as follows:

for (Entry<String, Map<String, String>> outerMapEntry : messagesByFactTypeAndCategory.entrySet()) {
        // do something with outerMapEntry
        System.out.println(outerMapEntry.getKey() + " => " + outerMapEntry.getValue());
        for (Entry<String, String> innerMapEntry : outerMapEntry.getValue().entrySet()) {
            // do something with inner map entry
            System.out.println(innerMapEntry.getKey() + " => " + innerMapEntry.getValue());

EDIT. Some explanation. Each outer map entry is a pair of String key and Map<String, String> value. So you can do something with both key and value on each iteration. For instance, you can print key and value as they are. Or you can traverse the value (it is a Map) and print each value entry separately in the inner loop.

I believe it's quite clear how to iterate "simple" map like Map<String, String>(see How to efficiently iterate over each Entry in a Map?), so there is no difficulty with traversing inner map.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download