Traverse a Map in Java

April 10, 2019 |

Iterate over Java MAP

Map is an interface and is a part of the java collections framework. Java collections framework provides a number of Map implementations like HashMap, TreeMap, LinkedHashMap etc. This post contains different ways of traversing through a HashMap, which are given below:
Following section illustrates different ways to traverse the map data. Since map contains key-value data, most of them traverse through the keys and get the corresponding data.
Map initialization
Following code creates instance of a TreeMap and puts 5 key-value pairs to it.
Map map = new TreeMap();
map.put(1,"A");
map.put(3,"C");
map.put(2,"B");
map.put(4,"D");
map.put(5,"E");
Iterator
Traverse using Iterator of the key set.
System.out.println("Print using Iterator");
Iterator it = map.keySet().iterator();

while (it.hasNext()) {
  Integer k = it.next();
  String  v = map.get(k);
  System.out.print( "Key=" + k + " Value=" + v);
}
Forloop
Following code traverse the map by using a for loop on the key set.
//For loop over the keySet
System.out.println("\nPrint using for loop");
for (Integer k : map.keySet()) {
  String  v = map.get(k);
  System.out.print( "Key=" + k + " Value=" + v);
}
Stream
Following code traverse the map using a stream on the key set.
System.out.println("\nPrint using stream");
map.keySet().stream().forEach(key -> {System.out.print ("Key=" + key + " Value=" + map.get(key)); });
forEach
Following code traverse using forEach method. forEach method was introduced in java 8.
System.out.println("\nPrint using forEach");
map.forEach((k, v) ->System.out.print( "Key=" + k + " Value=" + v)) ;