一、相同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);
文章介绍了在Java中复制List集合的三种方法:使用构造器、通过addAll方法以及Java8的StreamAPI。此外,还提到了不同List集合复制的情况,利用fastjson将一个List转换为另一个类型List的方法。



4121

被折叠的 条评论
为什么被折叠?



