Reputation: 1
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.
empID
and deptName
from departmentListMap<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
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