Iterating a Map using an Iterator
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | package main.java.lessons; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class IterateMapEntries { public static void main(String... args) { Map<String, String> map = new HashMap(); map.put("California", "Sacramento"); map.put("Texas", "Austin"); map.put("Florida", "Tallahassee"); map.put("Georgia", "Atlanta"); /** 1. Iterating Map using an Iterator. **/ Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = (Map.Entry) iterator.next(); System.out.println(String.format("Key:%s Value:%s", entry.getKey(), entry.getValue())); } } } |
Iterating a Map using for each loop over Map entries
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package main.java.lessons; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class IterateMapEntries { public static void main(String... args) { Map<String, String> map = new HashMap(); map.put("California", "Sacramento"); map.put("Texas", "Austin"); map.put("Florida", "Tallahassee"); map.put("Georgia", "Atlanta"); /** Iterating Map using for each loop over Map entries. **/ for (Map.Entry entry : map.entrySet()) { System.out.println(String.format("Key:%s Value:%s", entry.getKey(), entry.getValue())); } } } |
Iterating Map using java 1.8 forEach and lambda constructs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package main.java.lessons; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class IterateMapEntries { public static void main(String... args) { Map<String, String> map = new HashMap(); map.put("California", "Sacramento"); map.put("Texas", "Austin"); map.put("Florida", "Tallahassee"); map.put("Georgia", "Atlanta"); /** Iterating Map using java 1.8 forEach & lambda constructs. **/ map.forEach((k, v) -> { System.out.println(String.format("Key:%s Value:%s", k, v)); }); } } |
I'd highly recommend to start using java 1.8 forEach construct to iterate Map. It is so crisp and clear :)