Anand Kumar :
I am getting a list of managers from DB and now i have to populate each object of this list to another object i.e. employee and return it as a list (employeeList) to its calling function. Both Manager and Employee contains the same fields. I have to achieve this using lambda expression using stream.
Employee.java
public class Employee {
private String name;
private String designation;
private String active;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}}
Manager.java
public class Manager {
private String name;
private String designation;
private String active;
public String getActive() {
return active;
}
public void setActive(String active) {
this.active = active;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}}
ComponentImpl.java
public class ComponentImpl {
public List<Employee> catchAllEmployess () {
List<Manager> managers = DbOperation.collectManagers(2);
List<Employee> employees = new ArrayList<>();
for (Manager manager : managers) {
Employee employee = new Employee();
employee.setName(manager.getName());
employee.setDesignation(manager.getDesignation());
employee.setActive(manager.getActive());
employees.add(employee);
}
return employees;
}
}
Naman :
You can simplify the expression by including a constructor in Employee class as
Employee(String name, String designation, String active) {
this.name = name;
this.designation = designation;
this.active = active;
}
which can then be used as
List<Employee> employees = managers.stream()
.map(manager -> new Employee(manager.getName(), manager.getDesignation(), manager.getActive()))
.collect(Collectors.toList());