Search code examples
javahashmapentryset

Printing HashMap of HashMaps : Map.Entry or java8


I have a method which returns out hashmap of hashmaps

HashMap<String, HashMap<String, String>> mapofmaps = abcd(<String>, <Integer>);

I am trying to print the the outer hashmap using the following code

for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
            String key = entry.getKey();
            System.out.println(key);

      HashMap<String, String> value = entry.getValue();
            System.out.println(key + "\t" + value);
        }

I would like to iterate through the inner map. What would be the entryset variable there (??? in the code).

for (Entry<String, HashMap<String, String>> entry : mapofmaps.entrySet()) {
                String key = entry.getKey();
                System.out.println(key);
    for(Entry<String, HashMap<String, String>> entry : ????.entrySet()){
          HashMap<String, String> value = entry.getValue();
                System.out.println(key + "\t" + value);
            }}

Is my logic for printing the hashmaps correct? or is there a better way to do that?


Solution

  • It will be entry.getValue().entrySet() so

     for(Entry<String, String> innerEntry : entry.getValue().entrySet()){
    

    then you can use

        String key    = innerEntry.getKey();
        String value  = innerEntry.getValue();
    

    It is worth mentioning that, this can also be done Using java 8 Streams and lambda expressions

        HashMap<String, HashMap<String, String>> mapofmaps = new HashMap<>();
    
        HashMap<String,String> map1 = new HashMap<>();
        map1.put("map1_key1", "map1_value1");
    
        HashMap<String,String> map2 = new HashMap<>();
        map2.put("map2_key1", "map2_value1");
    
        mapofmaps.put("map1", map1);
        mapofmaps.put("map2", map2);
    

         // To print the keys and values
         mapofmaps.forEach((K,V)->{                 // mapofmaps entries
             V.forEach((X,Y)->{                     // inner Hashmap enteries
                 System.out.println(X+" "+Y);       // print key and value of inner Hashmap 
             });
         });
    

    mapofmaps.forEach((K,V) : This expects a lambda expressions which takes two inputs i.e Key (String) and Value (HashMap)

    V.forEach((X,Y)->{ : As this is applied on inner (V: fetched through previous foreach) hashmap so both Key and Value will be strings

    Reference for further reading :