Looping over a Map using forEach (Java 8 style)

Views: 126   

From Java8 you can use forEach to iterate over a Map, you can see it in action in following example.

import java.util.HashMap;
import java.util.Map;

public class IterateMapWithForEach {
    public static void main(String[] args) {
        Map<String, String> employeeIdVsName = new HashMap<>();

        employeeIdVsName.put("E01", "foo");
        employeeIdVsName.put("E02", "bar");
        employeeIdVsName.put("E03", "bar");

        employeeIdVsName.forEach((key, value) -> {
            System.out.println(key + ": " + value);
        });
    }
}

Output:

E02: bar
E01: foo
E03: bar
On By