3

I have map like this

Map<String, Map<String, List<String>>> m;

and i want to iterate through list

my logic is like this:

  1. first i getting the key of first map
  2. and getting the key of secondmap
  3. and from that key i am iterating the list.


for (Map m:m.keyset()){

    for (Map m1:m.getKey(){

        List<String> l = m1.getKey(){

        for (String s:l){
        }
    }
}

Is this correct?

I am confused to test it...please help me...:)

Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27
prasad
  • 61
  • 1
  • 1
  • 6

3 Answers3

6
Map<String, Map<String, List<String>>> m = new HashMap<>();

Iterate map using Entry:

for (Map.Entry<String, Map<String,List<String>> entry : m.entrySet()) {
    for (Map.Entry<String, List<String>> innerEntry : entry.entrySet()) {
        for (String elem : innerEntry) {
            ...
        }
    }
}

In terms of Java 8:

m.forEach((s, entry) -> entry.forEach(
        (s1, innerEntry) -> innerEntry.forEach(
                elem -> { ... }
        )
));
Sergei Rybalkin
  • 3,337
  • 1
  • 14
  • 27
2

You almost have it, here's what you're looking for

Map<String,Map<String,List<String>>> m = new HashMap<String, Map<String,List<String>>>();

for(String k : m.keySet()) {
    Map<String,List<String>> m1 = m.get(k);

    for(String k1 : m1.keySet()) {
        List<String> l = m1.get(k1);

        for (String s : l){
        }
    }
}
blue
  • 539
  • 3
  • 7
  • why we are using string k – prasad Sep 13 '16 at 15:09
  • there are three sections in an enhanced for-loop. the third part is the collection that is getting iterated. middle part is the local variable that represents the current value/object in the iteration. first part is the type of the objects in the collection. In your case, m.keySet() returns a Set of Strings. so String will be the type that has to go in the first part. – user3138997 Sep 13 '16 at 15:16
  • If your question is as to why for(String k : m.keySet()) is correct instead of for (Map m:m.keyset()) - ya? you need to understand the general structure of enhanced for loop eg: for(firstpart secondpart : thirdpart). – user3138997 Sep 13 '16 at 15:29
1

Simply iterate through values

    Map<String,Map<String,List<String>>> m = new HashMap<String, Map<String,List<String>>>();

    for(Map<String,List<String>> m2 : m.values()) {
        for(List<String> l : m2.values()) {
            for (String s : l){
            }
        }
    }
talex
  • 17,973
  • 3
  • 29
  • 66