Different Ways to Iterate over a Map in Java
Map<k, v>
A Map has Set of key value pairs. One key refers to only one value as such a map cannot contain duplicate keys.
package com.memorynotfound.collections.map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* @author MemoryNotFound.com
*/
public class MapIterateProgram {
public static void main(String... args){
Map<Integer, String> beers = new HashMap<Integer, String>();
beers.put(1, "La Chouffe");
beers.put(2, "Stella Artois");
beers.put(3, "Jupiler");
beers.put(4, "Westmalle Tripel");
// Using iterator
Iterator it = beers.entrySet().iterator();
while (it.hasNext()){
Map.Entry<Integer, String> beer = (Map.Entry)it.next();
beerPrinter(beer.getKey(), beer.getValue());
}
// Enhanced for loop
for (Map.Entry<Integer, String> beer : beers.entrySet()) {
beerPrinter(beer.getKey(), beer.getValue());
}
// JDK 8 for each with lambda
beers.forEach((k, v) -> beerPrinter(k, v));
// JDK 8 for each
beers.forEach(MapIterateProgram::beerPrinter);
}
private static void beerPrinter(Integer number, String brand){
System.out.println("favorite beer nr: " + number + " is " + brand);
}
}
note: If you want to use the JDK 8 way (lambda expression, method reference) you of course need to use the new JDK-8 in your project.
Sample output
favorite beer nr: 1 is La Chouffe
favorite beer nr: 2 is Stella Artois
favorite beer nr: 3 is Jupiler
favorite beer nr: 4 is Westmalle tripel