This example shows how to iterate a Map or HashMap in Java.
Iterating HashMap in different ways – Java Example – Iterator, For Loop, For Each Loop and While Loop.
Iterating Map or HashMap in different ways – Java Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class LoopMap { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "Jan"); map.put("2", "Feb"); map.put("3", "Mar"); map.put("4", "Apr"); map.put("5", "May"); map.put("6", "Jun"); System.out.println("Example 1..."); Iterator iterator = map.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("Example 2..."); for (Map.Entry<string, string> entry: map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } System.out.println("Example 3..."); for (Object key: map.keySet()) { System.out.println("Key : " + key.toString() + " Value : " + map.get(key)); } } } |