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。

posted @   南翔技校毕业后  阅读(720)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· 地球OL攻略 —— 某应届生求职总结
点击右上角即可分享
微信分享提示