In this article we will see how to convert a list to map in java 8 streams, and how to handle exception thrown by duplicate keys located in list.
class Employee {
	private int id;
	private String name;

	// Getter Setters, constructor and toString()

}



1) Convert a list to map in java 8

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

		Map<Integer, String> map = employees.stream().collect(Collectors.toMap(Employee::getId, Employee::getName));

		map.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
Output: Output of above code will look something like this:


key: 1 value:John
key: 2 value:Ben
key: 3 value:Zenny


2) Convert a list with duplicate keys to map in java 8

Using a third argument "(oldValue, newValue) -> oldValue)" one can decide what to do in case of a duplicate entry situation occurs.
		List<Employee> employees = new ArrayList<>();
		employees.add(new Employee(3, "Zenny"));
		employees.add(new Employee(1, "John"));
		employees.add(new Employee(2, "Ben"));
		employees.add(new Employee(2, "Ben"));

		Map<Integer, String> map = employees.stream()
				.collect(Collectors.toMap(Employee::getId, Employee::getName, (oldValue, newValue) -> oldValue));

		map.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
Output: Output of above code will look something like this:


key: 1 value:John
key: 2 value:Ben
key: 3 value:Zenny

  • By Techburps.com
  • Oct 6, 2018
  • Java 8