0

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?

1
  • If all argument constructor and new list was a possibility, you could have used streams such as 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. Commented Jul 14, 2020 at 3:38

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.