A Developer Gateway To IT World...

Techie Uncle Software Testing Core Java Java Spring C Programming Operating System HTML 5 Java 8 ES6 Project

How to loop HashMap in java?

Java HashMap

How to loop HashMap in java?

  • HashMap contains key and value pairs.

  • Key always be uniqe.

  • values can be duplicate but it will replace the old value and will staore the latest value entered corresponding to the key.

  • Java HashMap class may have one null key and multiple null values.





   
Consider the following values in HashMap are as below:


1).heera babu
2).value1
3).value2
4).techieuncle.com

Let's understand some basic concepts, in the below program code, you will see
         Iterator   itr = hm.keySet().iterator();
Here, the code in below program says that we are generating set of keys using keyset() method and then calling iterator() method in this set of keys.
Now, we can use while loop and then display all data based on key traversal.

        while(itr.hasNext())
  {
   System.out.println(hm.get(itr.next())); 
  }

Another way to understand the iterate the data.
Set  myset  =hm.keySet();
System.out.println("Set of Keys are: "+myset);

This code line will display data as below:
Set of Keys are: [null, 1, 2, 100]

Continue code:
Iterator itr =myset.iterator();
         while(itr.hasNext())
         {
              System.out.println(hm.get(itr.next()));
         }


 



   
Now the complete code is as below:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

public class TestMap
{
    public static void main(String a[])
    {
         HashMap hm = new HashMap();
         hm.put(1, "value1");
         hm.put(2, "value2");
         hm.put(null, "heera");
         hm.put(null, "heera babu");
         hm.put(100, "techieuncle.com");

         Iterator   itr = hm.keySet().iterator();
         while(itr.hasNext())
         {
              System.out.println(hm.get(itr.next()));
         }
    }
}


 





Console Output:
heera babu
value1
value2
techieuncle.com




 

LEARN TUTORIALS

.

.