How to Iterate a map or list in Java 8 using lambda

In Java 8 we can use forEcah to iterate over a list or map of objects, we will use "Employee" class list "employees" and "employeesMap" as example to iterate over it using java 8 lambda:
class Employee {
	private int id;
	private String name;

	public Employee(int id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}

}


1) Iterate a map in Java 8 using lambda

		Map<Integer, Employee> employeesMap = new HashMap<>();
		employeesMap.put(3, new Employee(3, "Zenny"));
		employeesMap.put(1, new Employee(1, "John"));
		employeesMap.put(2, new Employee(2, "Ben"));

		System.out.println("Iterating without lambda");

		Iterator<Entry<Integer, Employee>> iterator = employeesMap.entrySet().iterator();

		while (iterator.hasNext()) {
			Entry<Integer, Employee> entry = iterator.next();
			System.out.println("Key: " + entry.getKey() + "Value:" + entry.getValue());
		}

		System.out.println("Iterating using java 8 lambda");

		employeesMap.forEach((k, v) -> System.out.println("Key: " + k + "Value:" + v));

Output: Output of above code will look something like this:

Iterating without lambda

Key: 1Value:Employee [id=1, name=John]
Key: 2Value:Employee [id=2, name=Ben]
Key: 3Value:Employee [id=3, name=Zenny]

Iterating using java 8 lambda

Key: 1Value:Employee [id=1, name=John]
Key: 2Value:Employee [id=2, name=Ben]
Key: 3Value:Employee [id=3, name=Zenny]


2) Iterate a list in Java 8 using lambda

		List<Employee> employees = new ArrayList<>();
		employees.add(new Employee(3, "Zenny"));
		employees.add(new Employee(1, "John"));
		employees.add(new Employee(2, "Ben"));

		System.out.println("Iterating without lambda");

		for (Employee employee : employees)
			System.out.println(employee);

		System.out.println("Iterating using java 8 lambda");

		employees.forEach(i -> System.out.println(i));
Output: Output of above code will look something like this:

Iterating without lambda

Employee [id=3, name=Zenny]
Employee [id=1, name=John]
Employee [id=2, name=Ben]

Iterating using java 8 lambda

Employee [id=3, name=Zenny]
Employee [id=1, name=John]
Employee [id=2, name=Ben]