A Developer Gateway To IT World...

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

HashMap IQ in Adobe, Noida

How to iterate any Map in Java - techieuncle.com

How do we display all data of HashMap using loop?


Consider the following values in HashMap are as below:
heera babu
value1
value2
techieuncle.com
Let’s understand some basic concepts, in the below program code, you will see
         Iterator<String>   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<String>   itr =myset.iterator();
         while(itr.hasNext())
         {
              System.out.println(hm.get(itr.next()));
         }
        
Now the complete code is as below:
Program code:
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<String>   itr = hm.keySet().iterator();
         while(itr.hasNext())
         {
              System.out.println(hm.get(itr.next()));
         }
    }
}
Console Output:
heera babu
value1
value2

techieuncle.com

LEARN TUTORIALS

.

.