How to loop HashMap in java

In this tutorial we learn how to loop HashMap in java ,by For Loop and Iterator HashMap .

See Example:

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

public class Example {

public static void main(String[] args) {
HashMap<Integer, String>  hashMap = getHashMapKeyAndValue();
//For Loop hashMap
 System.out.println("For Loop:");
for(Map.Entry  map : hashMap.entrySet()){
System.out.println("Key :"+ map.getKey() + " & Value : " +map.getValue());
}
//WHILE LOOP & ITERATOR
        System.out.println("While Loop:");
     
        Iterator iterator = hashMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry map2 = (Map.Entry) iterator.next();
         System.out.println("Key: "+map2.getKey() + " & Value: " + map2.getValue());
       }

}
//Declare method
public static  HashMap<Integer, String> getHashMapKeyAndValue(){
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
hashMap.put(01, "Book1");
hashMap.put(05, "Book5");
hashMap.put(03, "Book3");
hashMap.put(04, "Book4");
hashMap.put(07, "Book7");
hashMap.put(02, "Book2");
hashMap.put(06, "Book6");
return hashMap;

}

}

// result :

For Loop:
Key :1 & Value : Book1
Key :2 & Value : Book2
Key :3 & Value : Book3
Key :4 & Value : Book4
Key :5 & Value : Book5
Key :6 & Value : Book6
Key :7 & Value : Book7
While Loop:
Key: 1 & Value: Book1
Key: 2 & Value: Book2
Key: 3 & Value: Book3
Key: 4 & Value: Book4
Key: 5 & Value: Book5
Key: 6 & Value: Book6
Key: 7 & Value: Book7


EmoticonEmoticon