package com.kkjavatutorials.client;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.kkjavatutorials.model.Employee;
/**
* @author KK JavaTutorials
*Convert List to Map using java 8 Stream API
*/
public class StreamApiExample {
public static void main(String[] args) {
Employee employee1 = new Employee(1002, "Sean", false, true, 10000.00);
Employee employee2 = new Employee(1072, "Marry", true, false, 15000.00);
Employee employee3 = new Employee(1882, "Sam", false, true, 30000.00);
Employee employee4 = new Employee(1992, "Sofiya", true, false, 3000.00);
Employee employee5 = new Employee(1112, "Raj", false, true, 16000.00);
Employee employee6 = new Employee(1772, "Hema", true, false, 9000.00);
//List of employees
List<Employee> empList = new ArrayList<>();
empList.add(employee1);
empList.add(employee2);
empList.add(employee3);
empList.add(employee4);
empList.add(employee5);
empList.add(employee6);
System.out.println("-------Getting Map from List where key = id, value = name in Map using Stream API----------");
// key = id, value = name
Map<Integer, String> empIdAndNameMap = empList.stream().collect(
Collectors.toMap(Employee::getId, Employee::getName));
System.out.println("empIdAndNameMap : " + empIdAndNameMap);
// Same as empIdAndNameMap but different syntax
// key = id, value = name
Map<Integer, String> empIdAndNameMap2 = empList.stream().collect(
Collectors.toMap(e -> e.getId(), e -> e.getName()));
System.out.println("empIdAndNameMap2 : " + empIdAndNameMap2);
System.out.println("-------Getting Map from List where key = id, value = salary in Map using Stream API----------");
// key = name, value = salary
Map<String, Double> empNameAndSalaryMap = empList.stream().collect(
Collectors.toMap(Employee::getName, Employee::getSalary));
System.out.println("empNameAndSalaryMap : " + empNameAndSalaryMap);
System.out.println("-------Getting Map from List where key = id, value = Employee Object in Map using Stream API----------");
//key = id, value = Employee Object
Map<Integer, Employee> collect = empList.stream().collect(Collectors.toMap(e->e.getId(),e->e));
System.out.println(collect);
}
}