In this example, we are going learn about what all the different ways to iterate Map in java.
File Name :MapIteration.java
/**
* This program explains different ways to loop Map in Java
*/
package com.becbe.java;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author BECBE
*
*/
public class MapIteration {
/**
* @param args
*/
public static void main(String[] args) {
//Map object declaration for employee
Map employeeMap = new HashMap();
//Adding 4 employee details
employeeMap.put("002345","Jake Merlin");
employeeMap.put("002475","Mike charle");
employeeMap.put("006345","Justin Renold");
employeeMap.put("002425","Kate");
System.out.println("Size of the Employee Map :"+employeeMap.size());
System.out.println("Type 1: using Iterator");
Iterator iterator = employeeMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
System.out.println("The key is : " + mapEntry.getKey()
+ ",value is :" + mapEntry.getValue());
}
System.out.println("Type 2 - Using entry set");
for (Map.Entry entry : employeeMap.entrySet()) {
System.out.println("Key : " + entry.getKey() + " Value : "
+ entry.getValue());
}
System.out.println("Type 3 using Key set");
for (Object key : employeeMap.keySet()) {
System.out.println("Key : " + key.toString() + " Value : "
+ employeeMap.get(key));
}
}
}
Output :
Size of the Employee Map :4 Type 1: using Iterator The key is : 002475,value is :Mike charle The key is : 002345,value is :Jake Merlin The key is : 002425,value is :Kate The key is : 006345,value is :Justin Renold Type 2 - Using entry set Key : 002475 Value : Mike charle Key : 002345 Value : Jake Merlin Key : 002425 Value : Kate Key : 006345 Value : Justin Renold Type 3 using Key set Key : 002475 Value : Mike charle Key : 002345 Value : Jake Merlin Key : 002425 Value : Kate Key : 006345 Value : Justin Renold
0 comments :
Post a Comment