Page.map方法的使用
Page.map方法的使用
1、前言
日常工作中,我们常常会有这样的场景:分页查询得到了结果,需要对dto的某个单独字段将进行赋值,这时候我们就会用到Page分页对象提供的map方法,用来转换Page内部对象。
2、实例
@Override
public ResponsePageVO<ProductStatDto> queryAll(ProductStatQueryCriteria criteria, Pageable pageable) {
// 分页查询得到结果
Page<ProductStat> page = this.queryPage(criteria, pageable);
// 得到dto集合
List<ProductStatDto> contentList = productStatMapper.toDto(page.getContent());
// 分别进行set值,并得到一个map
Map<Long, ProductStatDto> collect = contentList.stream().peek(x -> x.setCraftDto(craftService.findById(x.getCraftId())))
.collect(Collectors.toMap(ProductStatDto::getProductRowId, x -> x));
//page.map转换内部对象
Page<ProductStatDto> pageMap = page.map(x -> collect.get(x.getProductRowId()));
return PageUtil.toPageVo(pageMap);
}
3、源码
<U> Page<U> map(Function<? super T, ? extends U> converter);
page.map需要我们传入一个converter
@Override
public <U> Page<U> map(Function<? super T, ? extends U> converter) {
return new PageImpl<>(getConvertedContent(converter), getPageable(), total);
}
主要是实现了getConvertedContent(converter)方法
protected <U> List<U> getConvertedContent(Function<? super T, ? extends U> converter) {
Assert.notNull(converter, "Function must not be null!");
return this.stream().map(converter::apply).collect(Collectors.toList());
}
stream().map每一个操作,最后收集list。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结