List集合复制,以及不同List集合复制

文章介绍了在Java中复制List集合的三种方法:使用构造器、通过addAll方法以及Java8的StreamAPI。此外,还提到了不同List集合复制的情况,利用fastjson将一个List转换为另一个类型List的方法。
摘要由CSDN通过智能技术生成

一、相同List集合复制

方法1:构造器复制

QueryWrapper<BooksCategory> queryWrapper = new QueryWrapper<>();
//查询出来的List
List<BooksCategory> booksCategories = booksCategoryMapper.selectList(queryWrapper);
//复制后的List
List<BooksCategory> copy = new ArrayList<>(list);

 方法2:把一个集合加到一个空集合后面相当于复制

QueryWrapper<BooksCategory> queryWrapper = new QueryWrapper<>();
//查询出来的List
List<BooksCategory> booksCategories = booksCategoryMapper.selectList(queryWrapper);
//复制后的List
List<BooksCategory> copy = new ArrayList<>();
copy.addAll(list);

方法3:java8的Stream

QueryWrapper<BooksCategory> queryWrapper = new QueryWrapper<>();
//查询出来的List
List<BooksCategory> booksCategories = booksCategoryMapper.selectList(queryWrapper);
//复制后的List
List<BooksCategory> copy = booksCategories .stream()
.collect(Collectors.toList());

二、不同List集合复制

要先添加依赖

 <!-- fastjson:实现对象与JSON的相互转换 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        QueryWrapper<BooksCategory> queryWrapper = new QueryWrapper<>();
        //查询出来的List
        List<BooksCategory> booksCategories = booksCategoryMapper.selectList(queryWrapper);
        //复制后的List
        List<BooksCategoryVO> booksCategories1 =               
        JSON.parseArray(JSON.toJSONString(booksCategories),BooksCategoryVO.class);
        log.info("{}",booksCategories1);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值