How to Iterate HashMap with ArrayList in Java with Example

In this post, I will be sharing how to iterate HashMap with ArrayList in Java. Earlier, I have shared the difference between HashMap and ArrayList in Java.

Read Also: How to Convert HashMap to ArrayList in Java with Example

There are many ways to iterate over the HashMap in Java but here I am using enhanced for loop. The syntax of the map which we are going to iterate is given below:

HashMap<String, ArrayList<String>> map = new HashMap<>();


The key-value pairs are stored in the map like below:

USA   | Boston, NewYork, San-Francisco
UK    | Leicester, London, Birmingham
INDIA | Bangalore, Mumbai, Delhi

Iterate HashMap with ArrayList in Java

import java.util.*;
public class HashMapWithArrayList {
    public static void main(String args[]) {
    // Creating HashMap object with ArrayList as Value
    HashMap<String, ArrayList<String>> map = new HashMap<>();
    
    // Inserting key-value pairs in the above map 
    map.put("USA", new ArrayList(Arrays.asList("Boston","NewYork","San-Francisco")));
    map.put("INDIA", new ArrayList(Arrays.asList("Bangalore","Mumbai","Delhi")));
    map.put("UK", new ArrayList(Arrays.asList("Leicester","London","Birmingham")));
    
    // Iterating the Map
    for(Map.Entry<String, ArrayList<String>> entry : map.entrySet()){
        // Use entry.getKey() to fetch Key from entry object 
        System.out.println("Iterating cities of the country: "+ entry.getKey());
        // Iterating the ArrayList 
        // Use entry.getValue() to fetch ArrayList value from entry object 
        for(String city : entry.getValue())
        {
            System.out.println(city);
        }
    }    
  }
}


Output:
Iterating cities of the country: USA
Boston
NewYork
San-Francisco
Iterating cities of the country: UK
Leicester
London
Birmingham
Iterating cities of the country: INDIA
Bangalore
Mumbai
Delhi


That's all for today. Please mention in the comments in case you have any questions related to the how-to iterate HashMap with ArrayList in Java with example.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry