RHS
RHS

Reputation: 1

Java 8 streams: match and add parameters from one list to another

I am kinda new to streams and lambda. Looking for a tidier code for this use case.

I have two Lists of Object types

class Employee{
   long empId;
   String empName;
   String deptName
}

and

class Department{
   long deptId;
   String deptName;
   long empId;
}

Initially Employee list is populated only with empId and empName. And Department list populated with all the fields deptId,deptName,empId.

I have to populate corresponding deptName into Employee list from the Department list.

This is what I did.

  1. Made a map of empID and deptName from departmentList
  2. Iterate and match from the map
Map<Long,String> departmentMap = departmentList.stream()
                .collect((Collectors.toMap(Department::getEmpId, Department::getDeptName)));
employeeList.forEach(emp -> {
if(departmentMap.containsKey(emp.getEmpId())){
        emp.setDeptName(departmentMap.get(emp.getEmpId()));
}
});

Is there a cleaner or tidier way to handle this in Java 8/10?

Upvotes: 0

Views: 1938

Answers (1)

tdranv
tdranv

Reputation: 1340

If I understood correctly you are looking for something like:

List<Employee> employeeList = List.of(new Employee(1, "John"), new Employee(2, "Emily"));
List<Department> departmentList = List.of(new Department(1, "Dept 1", 1), new Department(2, "Dept 2", 2));

Map<Long, Department> departmentMap = departmentList.stream()
                .collect(toMap(department -> department.empId, department -> department));

employeeList.forEach(e -> e.deptName = departmentMap.get(e.empId).deptName);

You can use Collectors.toMap() to turn your List into a Map and then just go over your employeeList and assign each employee its department.

Upvotes: 1

Related Questions