java list的深拷贝

一般的写法:

//不使用stream拷贝list
        List<WarehouseStockItemBean> dtoList = new ArrayList<>();
        for (WarehouseStockItemBean warehouseStockItem : warehouseStockItemBeanList) {
            WarehouseStockItemBean d = new WarehouseStockItemBean();
            BeanUtils.copyProperties(warehouseStockItem, d);
            dtoList.add(d);
        }

使用java8的stream流写法:

warehouseStockItemBeanLists = warehouseStockItemBeanList.stream()
                .map(e -> {
                    WarehouseStockItemBean d = new WarehouseStockItemBean();
                    BeanUtils.copyProperties(e, d);
                    return d;
                })
                .collect(Collectors.toList());

两者在实现User对象拷贝到UserDTO对象时都是用了spring中内置的BeanUtils(这类工具类很多。我这里用的是spring自带的)

实现原理都是遍历集合拷贝对象然后添加到新集合

 

转自:http://www.3kkg.com/1095

侵删

posted @ 2021-01-19 11:16  卟萌  阅读(2042)  评论(0编辑  收藏  举报