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 @ 2022-10-25 08:52  南翔技校毕业后  阅读(783)  评论(0)    收藏  举报