0

I have the following nested Map defined in my class:

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

I'm trying but unable to traverse the messagesByFactTypeAndCategory map and get the data inside this to display in console.

Below is the code that I tried so far:

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

Any help is appreciated!

Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36
BobRoss
  • 53
  • 1
  • 11

1 Answers1

2

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.

Community
  • 1
  • 1
Vladimir Vagaytsev
  • 2,871
  • 9
  • 33
  • 36