How to iterate a Map in Java

How to iterate a Map in Java

There are several ways to iterate a Map in java.

  1. Iterate Map using iterator
  2. Iterate Map using keySet.
  3. Iterate Map using Entry Object.
  4. Using Lamda Expression.

Example to iterate a Map.

package com.code2succeed.collection;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HashMapExample {
	public static void main(String[] args) {
		HashMap<Integer, String> map = new HashMap<Integer, String>();
		
		map.put(1, "New York");
		map.put(2, "London");
		map.put(3, "Paris");
		map.put(4, "Mumbai");
		
		//Iterate HashMap using iterator
		Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
		System.out.println("Example 1");
		while (iterator.hasNext()) {
			Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>) iterator.next();
			System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
		}
		
		//Iterate using keySet.
		System.out.println("\nExample 2");
		for (Object key : map.keySet()) {
			System.out.println("Key : " + key + " Value : " + map.get(key));
		}
		
		//most efficient way. good to use if you are not using Java 8.
		System.out.println("\nExample 3");
		for (Map.Entry<Integer, String> entry : map.entrySet()) {
			System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
		}
		
		//Java 8 only, forEach and Lambda. recommend!
		System.out.println("\nExample 4");
		map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));
	}
}

Output

Example 1
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai
Example 2
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai
Example 3
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai
Example 4
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai

Leave a Reply

Your email address will not be published. Required fields are marked *