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.
- Made a map of
empID
anddeptName
from departmentList - 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?