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
empIDanddeptNamefrom 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?
List<Employee> updatedEmployees = employeeList.stream() .map(emp -> new Employee(emp.getEmpId(), emp.getEmpName(), departmentMap.getOrDefault(emp.getEmpId(), emp.getDeptName()))) .collect(Collectors.toList());or you are better with your current approach as well.