Java – Ways to iterate over List of HashMap

In this article, we will discuss different ways to iterate through List of HashMap. Already, in earlier articles, we have discussed following topics

Now, we will iterate through List of HashMap i.e.; a list containing HashMap with

  • key being String-type
  • values being String-type only

Different ways to iterate through List:

  • Regular/Standard/Traditional for-loop
  • Enhanced for-loop, introduced in Java 1.5 version
  • Iterating using Iterator of Collection interface
  • Iterating using ListIterator of List interface
  • Iterating List using forEach() in Java 1.8 version

Different ways to iterate through Map:

  • Using keySet() method and for-each loop
  • Using keySet() method and Iterator interface
  • Using entrySet() method and for-each loop
  • Using entrySet() method and Iterator interface
  • Using forEach() in Java 1.8

Ways to iterate over List of HashMap in Java:

We can pick any combination from above listed iterating ways, but we will limit our code to 3 demo examples i.e.,

  1. Using Iterator interface and entrySet() method of Map interface
  2. Using enhanced for-loop and keySet() method of Map interface
  3. Using forEach() method in Java 8 using Method reference

Let us move forward and discuss all possible ways to iterate List of HashMap of (String, String) type

1. Iterate using Iterator interface and loop through Map.entrySet()

  • Outer-List  –> iterated using Iterator interface
  • Inner-Map  –> iterated using enhanced for-loop, after getting entrySet();

IteratingArrayListUsingIteratorAndEntrySet.java

package in.bench.resources.string.methods;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class IteratingArrayListUsingIteratorAndEntrySet {

	public static void main(String[] args) {

		// HashMap 1: input preparation for WEST India Region
		Map<String, String> westIndiaStateCapital =
				new HashMap<String, String>();
		westIndiaStateCapital.put("Maharashtra", "Mumbai");
		westIndiaStateCapital.put("Gujarat", "Gandhinagar");
		westIndiaStateCapital.put("Rajasthan", "Jaipur");
		westIndiaStateCapital.put("Goa", "Panaji");

		// HashMap 2: input preparation for SOUTH India Region
		Map<String, String> southIndiaStateCapital =
				new HashMap<String, String>();
		southIndiaStateCapital.put("Andhra Pradesh", "Amaravati");
		southIndiaStateCapital.put("Karnataka", "Bengaluru");
		southIndiaStateCapital.put("Kerala","Thiruvananthapuram");
		southIndiaStateCapital.put("Tamil Nadu", "Chennai");
		southIndiaStateCapital.put("Telangana", "Hyderabad");

		// HashMap 3: input preparation for EAST India Region
		Map<String, String> eastIndiaStateCapital =
				new HashMap<String, String>();
		eastIndiaStateCapital.put("Bihar", "Patna");
		eastIndiaStateCapital.put("Jharkhand", "Ranchi");
		eastIndiaStateCapital.put("West Bengal", "Kolkata");
		eastIndiaStateCapital.put("Odisha", "Bhubaneswar");

		// HashMap 4: input preparation for SOUTH India Region
		Map<String, String> northIndiaStateCapital =
				new HashMap<String, String>();
		northIndiaStateCapital.put("Delhi", "New Delhi");
		northIndiaStateCapital.put("Himachal Pradesh", "Shimla");
		northIndiaStateCapital.put("Jammu n Kashmir", "Srinagar");
		northIndiaStateCapital.put("Punjab", "Chandigarh");

		// HashMap 5: input preparation for CENTRAL India Region
		Map<String, String> centralIndiaStateCapital =
				new HashMap<String, String>();
		centralIndiaStateCapital.put("Madhya Pradesh", "Bhopal");
		centralIndiaStateCapital.put("Uttar Pradesh", "Lucknow");
		centralIndiaStateCapital.put("Chhattisgarh", "Raipur");

		// create ArrayList and insert all 5 HashMap into it
		List<Map<String, String>> listOfIndianRegions =
				new ArrayList<Map<String, String>>();

		// add all 5 regions to AL
		listOfIndianRegions.add(westIndiaStateCapital);
		listOfIndianRegions.add(southIndiaStateCapital);
		listOfIndianRegions.add(eastIndiaStateCapital);
		listOfIndianRegions.add(northIndiaStateCapital);
		listOfIndianRegions.add(centralIndiaStateCapital);

		// temp variable to indicate zone/region
		int regionIndex = 1;

		// Way 1: Iterate using for-each and
		// loop through Map using entrySet() method
		System.out.println("Way 1: Iterate using for-each and"
				+ " loop through Map using entrySet() method");

		// get Iterator for looping through AL
		Iterator<Map<String, String>> iterator =
				listOfIndianRegions.iterator();

		// iterate AL using while-loop
		while(iterator.hasNext()) {

			System.out.println("\nIndia Region - " + regionIndex);
			System.out.println("=========================="
					+ "========================");

			Map<String, String> region = iterator.next();

			// getting entrySet() into Set
			Set<Entry<String, String>> entrySet =
					region.entrySet();

			// for-each loop
			for(Entry<String, String> entry : entrySet) {

				System.out.println("State : " + entry.getKey()
				+ "\tCapital : " + entry.getValue());
			}

			// increment region index by 1
			regionIndex++;
		}
	}
}

Output:

Way 1: Iterate using for-each and loop through Map using entrySet() method

India Region - 1
==================================================
State : Gujarat	Capital : Gandhinagar
State : Goa	Capital : Panaji
State : Maharashtra	Capital : Mumbai
State : Rajasthan	Capital : Jaipur

India Region - 2
==================================================
State : Karnataka	Capital : Bengaluru
State : Telangana	Capital : Hyderabad
State : Andhra Pradesh	Capital : Amaravati
State : Tamil Nadu	Capital : Chennai
State : Kerala	Capital : Thiruvananthapuram

India Region - 3
==================================================
State : Jharkhand	Capital : Ranchi
State : Bihar	Capital : Patna
State : Odisha	Capital : Bhubaneswar
State : West Bengal	Capital : Kolkata

India Region - 4
==================================================
State : Delhi	Capital : New Delhi
State : Himachal Pradesh	Capital : Shimla
State : Jammu n Kashmir	Capital : Srinagar
State : Punjab	Capital : Chandigarh

India Region - 5
==================================================
State : Madhya Pradesh	Capital : Bhopal
State : Uttar Pradesh	Capital : Lucknow
State : Chhattisgarh	Capital : Raipur

2. Iterate using enhanced for-loop and loop through Map.keySet()

  • Outer List –> iterated using enhanced for-loop
  • Inner Map –> iterated using Iterator interface, after getting keySet()

IteratingArrayListUsingForLoopAndKeySet.java

package in.bench.resources.list.of.hashmap;

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

public class IteratingArrayListUsingForLoopAndKeySet {

	public static void main(String[] args) {

		// HashMap 1: input preparation for WEST India Region
		Map<String, String> westIndiaStateCapital =
				new HashMap<String, String>();
		westIndiaStateCapital.put("Maharashtra", "Mumbai");
		westIndiaStateCapital.put("Gujarat", "Gandhinagar");
		westIndiaStateCapital.put("Rajasthan", "Jaipur");
		westIndiaStateCapital.put("Goa", "Panaji");

		// HashMap 2: input preparation for SOUTH India Region
		Map<String, String> southIndiaStateCapital =
				new HashMap<String, String>();
		southIndiaStateCapital.put("Andhra Pradesh", "Amaravati");
		southIndiaStateCapital.put("Karnataka", "Bengaluru");
		southIndiaStateCapital.put("Kerala","Thiruvananthapuram");
		southIndiaStateCapital.put("Tamil Nadu", "Chennai");
		southIndiaStateCapital.put("Telangana", "Hyderabad");

		// HashMap 3: input preparation for EAST India Region
		Map<String, String> eastIndiaStateCapital =
				new HashMap<String, String>();
		eastIndiaStateCapital.put("Bihar", "Patna");
		eastIndiaStateCapital.put("Jharkhand", "Ranchi");
		eastIndiaStateCapital.put("West Bengal", "Kolkata");
		eastIndiaStateCapital.put("Odisha", "Bhubaneswar");

		// HashMap 4: input preparation for SOUTH India Region
		Map<String, String> northIndiaStateCapital =
				new HashMap<String, String>();
		northIndiaStateCapital.put("Delhi", "New Delhi");
		northIndiaStateCapital.put("Himachal Pradesh", "Shimla");
		northIndiaStateCapital.put("Jammu n Kashmir", "Srinagar");
		northIndiaStateCapital.put("Punjab", "Chandigarh");

		// HashMap 5: input preparation for CENTRAL India Region
		Map<String, String> centralIndiaStateCapital =
				new HashMap<String, String>();
		centralIndiaStateCapital.put("Madhya Pradesh", "Bhopal");
		centralIndiaStateCapital.put("Uttar Pradesh", "Lucknow");
		centralIndiaStateCapital.put("Chhattisgarh", "Raipur");

		// create ArrayList and insert all 5 HashMap into it
		List<Map<String, String>> listOfIndianRegions =
				new ArrayList<Map<String, String>>();

		// add all 5 regions to AL
		listOfIndianRegions.add(westIndiaStateCapital);
		listOfIndianRegions.add(southIndiaStateCapital);
		listOfIndianRegions.add(eastIndiaStateCapital);
		listOfIndianRegions.add(northIndiaStateCapital);
		listOfIndianRegions.add(centralIndiaStateCapital);

		// temp variable to indicate zone/region
		int regionIndex = 1;

		// Way 2: Iterate using Iterator interface and
		// loop through Map using keyset() method
		System.out.println("Way 2: Iterate using"
				+ " Iterator interface and "
				+ "loop through Map using keyset() method");
		for(Map<String, String> region : listOfIndianRegions) {

			System.out.println("\nIndia Region - " + regionIndex);
			System.out.println("============================"
					+ "======================");

			// get entrySet() into Set
			Set<String> setOfIndianStates = region.keySet();

			// Collection Iterator
			Iterator<String> iterator =
					setOfIndianStates.iterator();

			// iterate using while-loop after getting Iterator
			while(iterator.hasNext()) {

				String key = iterator.next();
				System.out.println("State : " + key
						+ "\tCapital : " + region.get(key));
			}

			// increment region index by 1
			regionIndex++;
		}
	}
}

Output:

Way 2: Iterate using Iterator interface and loop through Map using keyset() method

India Region - 1
==================================================
State : Gujarat	Capital : Gandhinagar
State : Goa	Capital : Panaji
State : Maharashtra	Capital : Mumbai
State : Rajasthan	Capital : Jaipur

India Region - 2
==================================================
State : Karnataka	Capital : Bengaluru
State : Telangana	Capital : Hyderabad
State : Andhra Pradesh	Capital : Amaravati
State : Tamil Nadu	Capital : Chennai
State : Kerala	Capital : Thiruvananthapuram

India Region - 3
==================================================
State : Jharkhand	Capital : Ranchi
State : Bihar	Capital : Patna
State : Odisha	Capital : Bhubaneswar
State : West Bengal	Capital : Kolkata

India Region - 4
==================================================
State : Delhi	Capital : New Delhi
State : Himachal Pradesh	Capital : Shimla
State : Jammu n Kashmir	Capital : Srinagar
State : Punjab	Capital : Chandigarh

India Region - 5
==================================================
State : Madhya Pradesh	Capital : Bhopal
State : Uttar Pradesh	Capital : Lucknow
State : Chhattisgarh	Capital : Raipur

Note:

  • keySet(); and entrySet(); methods of Map interface from Java 1.2 version
  • Iterator interface for iterating comes from Java 1.2 version
  • Whereas enhanced for-each loop introduced in Java 1.5 version

3. Using Java 8’s Iterable.forEach() method

  • forEach(System.out::println); –> this line prints entire output in console (in {key-value} pair format)

IteratingArrayListUsingJava8ForEach.java

package in.bench.resources.list.of.hashmap;

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

public class IteratingArrayListUsingJava8ForEach {

	public static void main(String[] args) {

		// HashMap 1: input preparation for WEST India Region
		Map<String, String> westIndiaStateCapital =
				new HashMap<String, String>();
		westIndiaStateCapital.put("Maharashtra", "Mumbai");
		westIndiaStateCapital.put("Gujarat", "Gandhinagar");
		westIndiaStateCapital.put("Rajasthan", "Jaipur");
		westIndiaStateCapital.put("Goa", "Panaji");

		// HashMap 2: input preparation for SOUTH India Region
		Map<String, String> southIndiaStateCapital =
				new HashMap<String, String>();
		southIndiaStateCapital.put("Andhra Pradesh", "Amaravati");
		southIndiaStateCapital.put("Karnataka", "Bengaluru");
		southIndiaStateCapital.put("Kerala","Thiruvananthapuram");
		southIndiaStateCapital.put("Tamil Nadu", "Chennai");
		southIndiaStateCapital.put("Telangana", "Hyderabad");

		// HashMap 3: input preparation for EAST India Region
		Map<String, String> eastIndiaStateCapital =
				new HashMap<String, String>();
		eastIndiaStateCapital.put("Bihar", "Patna");
		eastIndiaStateCapital.put("Jharkhand", "Ranchi");
		eastIndiaStateCapital.put("West Bengal", "Kolkata");
		eastIndiaStateCapital.put("Odisha", "Bhubaneswar");

		// HashMap 4: input preparation for SOUTH India Region
		Map<String, String> northIndiaStateCapital =
				new HashMap<String, String>();
		northIndiaStateCapital.put("Delhi", "New Delhi");
		northIndiaStateCapital.put("Himachal Pradesh", "Shimla");
		northIndiaStateCapital.put("Jammu n Kashmir", "Srinagar");
		northIndiaStateCapital.put("Punjab", "Chandigarh");

		// HashMap 5: input preparation for CENTRAL India Region
		Map<String, String> centralIndiaStateCapital =
				new HashMap<String, String>();
		centralIndiaStateCapital.put("Madhya Pradesh", "Bhopal");
		centralIndiaStateCapital.put("Uttar Pradesh", "Lucknow");
		centralIndiaStateCapital.put("Chhattisgarh", "Raipur");

		// create ArrayList and insert all 5 HashMap into it
		List<Map<String, String>> listOfIndianRegions =
				new ArrayList<Map<String, String>>();

		// add all 5 regions to AL
		listOfIndianRegions.add(westIndiaStateCapital);
		listOfIndianRegions.add(southIndiaStateCapital);
		listOfIndianRegions.add(eastIndiaStateCapital);
		listOfIndianRegions.add(northIndiaStateCapital);
		listOfIndianRegions.add(centralIndiaStateCapital);

		// Way 3: Using Iterable.forEach() in Java 8 version
		System.out.println("Way 3: Using "
				+ "Iterable.forEach() in Java 8 version");

		//  Iterating using forEach() in Java 8
		listOfIndianRegions.forEach(System.out::println);
	}
}

Output:

Way 3: Using Iterable.forEach() in Java 8 version

{Gujarat=Gandhinagar, Goa=Panaji,
		Maharashtra=Mumbai, Rajasthan=Jaipur}

{Karnataka=Bengaluru, Telangana=Hyderabad,
		Andhra Pradesh=Amaravati, Tamil Nadu=Chennai,
		Kerala=Thiruvananthapuram}

{Jharkhand=Ranchi, Bihar=Patna,
		Odisha=Bhubaneswar, West Bengal=Kolkata}

{Delhi=New Delhi, Himachal Pradesh=Shimla,
		Jammu n Kashmir=Srinagar, Punjab=Chandigarh}

{Madhya Pradesh=Bhopal, Uttar Pradesh=Lucknow,
		Chhattisgarh=Raipur}

From above example, ArrayList

  • allows duplicate records/elements to be stored
  • null object is allowed (any number of times and all are counted)
  • while iterating, elements/records are retrieved as per insertion-order

Related Articles:

Happy Coding !!
Happy Learning !!

Java - Collection Interview question and answers
Java - Sorting list of objects on multiple fields using Comparator