将lambda替换为包含新关键字的方法引用

时间:2018-10-24 09:23:40

标签: java lambda java-8

List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());

如何用方法参考替换此(inv -> new Employee(inv)) lambda。

完整代码参考:

package org.learn.copy;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class DeepCopy {
    public static void main(String[] args){
        Employee emp = new Employee();
        emp.setName("Hello");
        emp.setRollNumber("12345");

        Employee emp1 = new Employee();
        emp1.setName("Hi");
        emp1.setRollNumber("123456");

        List<Employee> empList = new ArrayList<>();
        empList.add(emp);
        empList.add(emp1);

        List<Employee> empListRef = empList;

        System.out.println("empList Obj: "+empList.get(0).getName());
        System.out.println("empListRef Obj: "+empListRef.get(0).getName());

        List<Employee> empListObjDeepCopy = empListRef.stream().map(inv -> new Employee(inv)).collect(Collectors.toList());

        empListObjDeepCopy.get(0).setName("Hi");

        System.out.println("empList Obj: "+empList.get(0).getName());
        System.out.println("empListRef Obj: "+empListRef.get(0).getName());
        System.out.println("empListObjDeepCopy Obj: "+empListObjDeepCopy.get(0).getName());
    }
}

class Employee {
    private String name; 
    private String rollNumber;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getRollNumber() {
        return rollNumber;
    }
    public void setRollNumber(String rollNumber) {
        this.rollNumber = rollNumber;
    }
    public Employee(Employee employee) {
        this.name = employee.name;
        this.rollNumber = employee.rollNumber;
    }
    public Employee() {
        super();
    }   
}

1 个答案:

答案 0 :(得分:1)

使用.map(Employee::new)模棱两可,因为Employee类中有两个构造函数。尝试只留下一个。