How to Iterate a HashMap in Java?

How to Iterate a HashMap in Java?


There are many ways to iterate a HashMap in Java.

Using an Iterator to iterate a HashMap.


package com.codeforsolution.logical.java8;

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

public class HashMapIterateTest {
    public static void main(String[] args) {
        Map<Integer,String> hm= new HashMap<>();
        hm.put(1,"Ram");
        hm.put(2,"Shyam");
        hm.put(3, "vishal");
        hm.put(4, "Anant patil");
        hm.put(5, "satya");
        hm.put(6,"Rakesh");
        Iterator<Map.Entry<Integer,String>> newIterator = hm.entrySet().iterator();

        while (newIterator.hasNext()){
            Map.Entry<Integer,String>  newHm = newIterator.next();
            System.out.println(newHm.getKey() +" = " + newHm.getValue());
        }
    }

}
		
       
Output:- 
1 = Ram
2 = Shyam
3 = vishal
4 = Anant patil
5 = satya
6 = Rakesh

Using Lambda Expressions forEach method

//Using Lambda Expressions forEach
hm.forEach((key,value) -> System.out.println( key + " = " +value));

Using Stream API

//using Stream API
hm.entrySet().stream().forEach(map -> System.out.println(map.getKey() + " = "+map.getValue()));


Github link for the codes  HashMapIterateTest

Post a Comment (0)
Previous Post Next Post