java

How to iterate through a HashMap in Java

In this tutorial, we are going to see how to iterate through a Hashmap in Java, using different methods:

  • By using For loop
  • By using While Loop with Iterator

 

Java Program to iterate through a HashMap using For loop
import java.util.*; 

public class Main 
{ 
    public static void main(String args[]) 
    { 
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        // add elements to HashMap
        map.put(1, "Alex");
        map.put(2, "Emily");
        map.put(3, "Thomas");
        map.put(4, "Yohan");

        //iterate through the HashMap using For loop
        for (Map.Entry m : map.entrySet()) {
           System.out.println("ID: "+m.getKey()+", Name: "+m.getValue());
        }
    }
}

Output:

ID: 1, Name: Alex
ID: 2, Name: Emily
ID: 3, Name: Thomas
ID: 4, Name: Yohan
 

Java Program to iterate through a HashMap using While Loop with Iterator
import java.util.*; 
  
public class Main 
{ 
    public static void main(String args[]) 
    { 
        HashMap<Integer, String> map = new HashMap<Integer, String>();
        // ajouter des éléments au HashMap
        map.put(1, "Alex");
        map.put(2, "Emily");
        map.put(3, "Thomas");
        map.put(4, "Yohan");

        //iterate through the HashMap using While loop + Iterator
        Iterator it = map.entrySet().iterator();
        while (it.hasNext()) {
           Map.Entry m = (Map.Entry) it.next();
           System.out.println("ID: "+m.getKey()+", Name: "+m.getValue());
        }
    }
}

Output:

ID: 1, Name: Alex
ID: 2, Name: Emily
ID: 3, Name: Thomas
ID: 4, Name: Yohan
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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