Split one object into List of objects - JAVA8 Solution required

Viewed 329

I have the following code where i have a single employee object with multiple roles. i want to split this single employee object into multiple employee objects with each object have just ONE role.

public class Employee {
   private String empId;
   private String empName;
   private List<String> empRoles;
 }

Now i have a method with return type List

public List<Employee> splitEmployeObj(Employee emp) {
   // code logic goes here 
 }
   // sample input : { empId:'123',empName:'john',empRoles:['Developer','Tester'] }
   // sample output : [ { empId:'123', empName:'john',empRoles : ['Developer'] },
                        { empId:'123', empName:'john',empRoles : ['Tester']]

can someone help with an efficient java8 solution.

1 Answers

Stream over the roles and map to a new Employee:

public List<Employee> splitEmployeObj(Employee emp) {
    return emp.getEmpRoles()
            .stream()
            .map(role -> new Employee(emp.getEmpId(), emp.getEmpName(), Collections.singletonList(role)))
            .collect(Collectors.toList());
}
Related