Java 8 列表副本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47833095/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 09:50:06  来源:igfitidea点击:

Java 8 List copy

javaarraylistjava-8

提问by Makky

I have an employee object

我有一个员工对象

I Cannot update the employee Object

我无法更新员工对象

public class Employee {

    public Employee(Integer id, Integer age, String gender, String fName, String lName) {
        this.id = id;
        this.age = age;
        this.gender = gender;
        this.firstName = fName;
        this.lastName = lName;
    }

    private Integer id;
    private Integer age;
    private String gender;
    private String firstName;
    private String lastName;

I am initially setting a employee list but want to create copy of that and then make changes to it. Even though I am creating new list its still changing the original list

我最初正在设置员工列表,但想创建该列表的副本,然后对其进行更改。即使我正在创建新列表,它仍在更改原始列表

public class ListTest {

    public static void main(String[] args) {

        List<Employee> employeeList = new ArrayList<>();
        Employee employee = new Employee(1, 1, "MALE", "TEST", "TEST");
        employeeList.add(employee);

        List<Employee> listTwo = new ArrayList<>();
        listTwo.addAll(employeeList);

        listTwo.get(0).setAge(11);

        System.out.println(employeeList.get(0).getAge());

    }
}

The output is coming as 11.

输出为 11。

Is there any easier way to clone from original list and any changes should not be applied to original list object and just the new list I created

有没有更简单的方法可以从原始列表中克隆,任何更改都不应应用于原始列表对象,而仅应用于我创建的新列表

回答by glglgl

It is not changing the original list, but it is changing the object which is contained in both lists.

它不会更改原始列表,而是更改包含在两个列表中的对象。

In cases like this, it might be very useful to make the employee objects unmodifiable and provide a possibility to create a copy object with changed properties with respect to the original one.

在这种情况下,使员工对象不可修改并提供创建副本对象的可能性可能非常有用,该副本对象具有相对于原始对象已更改的属性。

I am not sure if clone()creates a deep copy of the object. If so, all is fine, if not, you can use streams to create a deep copy.

我不确定是否clone()创建了对象的深层副本。如果是这样,一切都很好,如果不是,您可以使用流来创建深拷贝

If you absolutely cannot modify the Employeeobject (not even add a copy constructor), you can do it like this:

如果你绝对不能修改Employee对象(甚至不添加复制构造函数),你可以这样做:

public static Employee clone(Employee original) {
    return new Employee(original.getID(), original.getAge(), original.getGender(), original.getFirstName(), original.getLastName());
}

and then do

然后做

employeeList.stream().map(item -> clone(item)).collect(Collectors.toList());

or just

要不就

employeeList.stream().map(<thisclassname>::clone).collect(Collectors.toList());

(essentially the same what Uata suggests, but do the copying on your own).

(基本上与 Uata 建议的相同,但请自行复制)。

回答by Uata

First make a copy constructor in your Employee class:

首先在你的 Employee 类中创建一个复制构造函数:

    public Employee(Employee employee) {
        this.id = employee.id;
        this.age = employee.age;
        this.gender = employee.gender;
        this.firstName = employee.firstName;
        this.lastName = employee.lastName;
    }

And then you can make a deep copy with Java 8 streams:

然后您可以使用 Java 8 流进行深度复制:

List<Employee> listTwo = employeeList.stream().map(item -> new Employee(item)).collect(Collectors.toList());

回答by Lino

As you can not change the Employee class itself you can make a helper method which deep copies a Employeeinstance (you could of course also invoke the constructor directly, but I find a simple method cleaner):

由于您无法更改 Employee 类本身,因此您可以创建一个深度复制Employee实例的辅助方法(您当然也可以直接调用构造函数,但我找到了一个简单的方法清洁器):

public static Employee copy(Employee original){
    return new Employe(original.id, original.age, original.gender, original.fname, original.lname);
}

and with that you then can Stream the list and copy each element with a map operation:

然后,您可以流式传输列表并使用映射操作复制每个元素:

List<Employee> employeesCopy = employees.stream() // Stream<Employee>
    .map(e -> copy(e))                            // Stream<Employee>
    .collect(Collectors.toList());                // List<Employee>