Reputation: 393
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;
}
}
Upvotes: 4
Views: 3064
Reputation: 2950
This is obviously a contrived example so this answer might not be applicable, but the way these classes are written screams to me that either Manager
should extend Employee
or they should at least extend a common interface. Then the whole operation might not even be necessary anymore.
Upvotes: 1
Reputation: 32028
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());
Upvotes: 2