Java 8 – Iterate through Map Example

Java 8 – Iterate through Map

In this example, We will show simple example program about, How to Iterate through map in Java 8. The example program has been tested and shared in the same post.

Example Program

package com.dineshkrish;

import java.util.Map;
import java.util.TreeMap;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class MapForEach {

	public static void main(String[] args) {
		
		// defining the map object
		Map<Integer, String> employees = new TreeMap<Integer, String>();
		
		// adding the elements to the map
		employees.put(101, "Dinesh");
		employees.put(102, "Krishnan");
		employees.put(103, "John");
		employees.put(104, "James");
		employees.put(105, "William");
		
		// iterating the elements
		employees.forEach((k,v) -> System.out.println(k+" - "+v));
		
	}
}

Output

101 - Dinesh
102 - Krishnan
103 - John
104 - James
105 - William

References

1. JavaDoc – Map Interface
2. JavaDoc – TreeMap Class
3. Java 8 – Map forEach() method