How to iterate a Map in Java
This tutorial shows several ways for iterating a Map in Java.
1- Entry Set
The common way for iterating a Map in Java is through entrySet() method as the following:
1 2 3 4 5 6 7 8 | private static void iterateMapUsingEntrySet(Map<String, Double> studentGrades) { for(Entry<String, Double> entry : studentGrades.entrySet()) { System.out.println("Key = " + entry.getKey()); System.out.println("Value = " + entry.getValue()); } } |
2- Iterator
You can also use entrySet() along with iterator() methods to iterate a Map through an Iterator:
1 2 3 4 5 6 7 8 9 | private static void iterateMapUsingIterator(Map<String, Double> studentGrades) { Iterator entries = studentGrades.entrySet().iterator(); for(Entry entry = (Entry) entries.next(); entries.hasNext();) { System.out.println("Key = " + entry.getKey()); System.out.println("Value = " + entry.getValue()); } } |
3- keySet()
Using keySet() method, you can retrieve all the keys of the map and then get their corresponding value:
1 2 3 4 5 6 7 8 | private static void iterateMapUsingKeySet(Map<String, Double> studentGrades) { for(String key : studentGrades.keySet()) { System.out.println("Key = " + key); System.out.println("Value = " + studentGrades.get(key)); } } |
4- values()
You can use values() method to retrieve all the values as a Collection without their corresponding keys.
1 2 3 4 5 6 7 | private static void iterateMapUsingValues(Map<String, Double> studentGrades) { for(Double value : studentGrades.values()) { System.out.println("Value = " + value); } } |
5- Java 8
With Java 8, you can iterate over a Map through one line using forEach() method:
1 2 3 4 5 6 7 8 | private static void iterateMapUsingJava8(Map<String, Double> studentGrades) { studentGrades.forEach((key,value) -> { System.out.println("Key = " + key); System.out.println("Value = " + value); }); } |
Leave a Reply