Looping Map in Java

  1. Home
  2. Blog
  3. Looping Map in Java

Looping Map in Java

Below code snippet shows how to loop a Map or HashMap in Java.

Map<String, String> map = new HashMap<String, String>();
map.put("1", "Mon"); 
map.put("2", "Tue");
map.put("3", "Wed");
  
//loop a Map
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
}
System.out.println("####################");
//Java 8 only, forEach and Lambda
map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v));

SysOut

Key : 1 Value :Mon
Key : 2 Value :Tue
Key : 3 Value :Wed
####################
Key : 1 Value :Mon
Key : 2 Value :Tue
Key : 3 Value :Wed

3 ways to loop or iterate Map in Java.

package com.ms;

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

public class MapExample {

    public static void main(String[] args) {

      // initial a Map
      Map<Integer, String> map = new HashMap<Integer, String>();
      map.put(1, "Mon");
      map.put(2, "Tue");
      map.put(3, "Wed");
      map.put(4, "Thu");
      map.put(5, "Fri");
      map.put(6, "Sat");
      map.put(7, "Sun");
      
      System.out.println("Example 1");
      for (Map.Entry<Integer, String> entry : map.entrySet()) {
        System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
      }
      System.out.println("##########################");
      System.out.println("Example 2");
      for (Object key : map.keySet()) {
        System.out.println("Key : " + key.toString() + " Value : " + map.get(key));
      }
      System.out.println("##########################");
      System.out.println("Example 3");
      Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator();
      while (iterator.hasNext()) {
        Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>) iterator.next();
        System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue());
      }
  }
}

SysOut

Example 1
Key : 1 Value : Mon
Key : 2 Value : Tue
Key : 3 Value : Wed
Key : 4 Value : Thu
Key : 5 Value : Fri
Key : 6 Value : Sat
Key : 7 Value : Sun
##########################
Example 2
Key : 1 Value : Mon
Key : 2 Value : Tue
Key : 3 Value : Wed
Key : 4 Value : Thu
Key : 5 Value : Fri
Key : 6 Value : Sat
Key : 7 Value : Sun
##########################
Example 3
Key : 1 Value :Mon
Key : 2 Value :Tue
Key : 3 Value :Wed
Key : 4 Value :Thu
Key : 5 Value :Fri
Key : 6 Value :Sat
Key : 7 Value :Sun

 

 

Let's Share
Show Buttons
Hide Buttons