如何从Lambda表达式中的另一个对象设置一个对象

时间:2018-10-13 11:38:53

标签: java lambda java-8 java-stream

我从数据库中获得了一个经理列表,现在我必须将该列表的每个对象填充到另一个对象,即employee,并将其作为列表(employeeList)返回到其调用函数。经理和雇员都包含相同的字段。我必须使用使用流的lambda表达式来实现此目的。

Employee.java

data2 = data
data2[which(data > 0,arr.ind = T)] = "A"  
data2[which(data <= 0,arr.ind = T)] = "B"
data = data2

Manager.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;
}}

ComponentImpl.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;
}}

}

2 个答案:

答案 0 :(得分:2)

您可以通过在Employee类中包含一个构造函数来简化表达式

Employee(String name, String designation, String active) {
        this.name = name;
        this.designation = designation;
        this.active = active;
    }

然后可以用作

List<Employee> employees = managers.stream()
                .map(manager -> new Employee(manager.getName(), manager.getDesignation(), manager.getActive()))
                .collect(Collectors.toList());

答案 1 :(得分:2)

这显然是一个人为的示例,因此此答案可能不适用,但是这些类的编写方式对我大叫:require_once '/vendor/xplore-php-sdk/xplore-php-sdk.php'; $query = new XPLORE('h3zjkzrgvt6fyx2huwn65hy9'); $query->doi($doi); $result = $query->callAPI(); 应该扩展Manager,或者至少应该扩展一个公共接口。那么整个操作甚至都不再必要。