Wednesday, 29 July 2015

How to iterate a Hash map of arraylists of String in Java?

This program is about how to iterate a HashMap that contains arraylists of String.

In the code- In the method getMap() I have created 3 lists and stored them in the HashMap.
Though there are several ways to iterate over a HashMap, but here I have used the for-each loop for iterating the created hash map. Every Map.Entry object will be a key-value pair where value will be the array list stored with the given key. That's the list I am getting by using listEntry.getValue().
In the second for-each loop iterating over the list, retrieved using listEntry.getValue() and then printing the values that are in the list.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapLoop {

    public static void main(String[] args) {
        MapLoop mapLoop = new MapLoop();
        Map<String, List<String>> cityMap = mapLoop.getMap();
        int i = 0;
        // iterating over a map
        for(Map.Entry<String, List<String>> listEntry : cityMap.entrySet()){
            System.out.println("Iterating list number - " + ++i);
            // iterating over a list
            for(String cityName : listEntry.getValue()){
                System.out.println("City - " + cityName);
            }
        }
    }
    
    /**
     * A method to create a list and store it in a Map
     * @return
     */
    private Map<String, List<String>> getMap(){
        Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
        // First List
        List<String> temp = new ArrayList<String>();  
        temp.add("Delhi");
        temp.add("Mumbai");
        // Putting first list in the map
        cityMap.put("1", temp);
        // Second List
        temp = new ArrayList<String>();  
        temp.add("Hyderabad");
        temp.add("Bangalore");
        // Putting second list in the map
        cityMap.put("2", temp);
        // Third List
        temp = new ArrayList<String>();
        temp.add("Kolkata");
        temp.add("Chennai");
        // Putting third list in the map
        cityMap.put("3", temp);
        return cityMap;
    }
}
Output
Iterating list number - 1
City - Delhi
City - Mumbai
Iterating list number - 2
City - Hyderabad
City - Bangalore
Iterating list number - 3
City - Kolkata
City - Chennai

That's all for this topic How to iterate a Hash map of arraylists of String in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How HashMap internally works in Java
  2. How to loop/iterate an arraylist in Java
  3. How to loop through a map in Java
  4. Count total number of times each character appears in a String
  5. How to sort arraylist of custom objects in Java

You may also like -

>>>Go to Java Programs page

No comments:

Post a Comment