java stream 拷贝对象List集合

public class Test {
    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(new Tem(1));
        list.add(new Tem(2));
        System.err.println("对象List = " + JSONObject.toJSONString(list));
        List newList = list.stream().map(e -> {
            Tem t = new Tem();
            BeanUtils.copyProperties(e, t);
            return t;
        }).collect(Collectors.toList());
        System.err.println("拷贝出来的List = " + JSONObject.toJSONString(newList));
        list.get(0).setId(44);
        System.err.println("修改list集合对象信息之后  = " + JSONObject.toJSONString(list));
        System.err.println("拷贝出来的List = " + JSONObject.toJSONString(newList));

    }
}
class Tem {
    public Tem() {
    }

    public Tem(int id) {
        this.id = id;
    }

    private int id;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

运行结果:ERROR 忽略


image.png

你可能感兴趣的:(java stream 拷贝对象List集合)