List转Page对象!看这篇就够了,附实验结果

List 转 Page 对象

处理统计等数据时分页展示、第三方接口仅返回list,需分页显示等需求


public class ConvertList2PageVOUtil {
    /**
     * List 转 Page 对象
     * @param list
     * @param page 必须大于0
     * @param size 必须大于0
     * @param <T>
     * @return
     */
    public static <T> Page<T> convertList2PageVO(final List<T> list, final Integer page, final Integer size) {
        if (page < 1 && size < 1){
            throw new BaseRetException(BaseRet.createFailureRet("页参数或页大小参数错误!"));
        }
        Pageable pageable = new PageRequest(page - 1, size);
        if (CollectionUtils.isEmpty(list)) {
            return new PageImpl<>(new ArrayList<>(0), pageable, 0);
        }
        final List<T> ingredientVOS = list;
        final List<List<T>> partition = Lists.partition(list, pageable.getPageSize());
        List<T> pageContent = partition.get(pageable.getPageNumber());
        return new PageImpl<>(pageContent, pageable, ingredientVOS.size());
    }

    /**
     * List 转 Page 对象
     * @param list
     * @param pageable 分页参数
     * @param <T>
     * @return
     */
    public static <T> Page<T> convertList2PageVO(final List<T> list,final Pageable pageable) {
        if (CollectionUtils.isEmpty(list)) {
            return new PageImpl<>(new ArrayList<>(0), pageable, 0);
        }
        final List<T> ingredientVOS = list;
        final List<List<T>> partition = Lists.partition(list, pageable.getPageSize());
        List<T> pageContent = partition.get(pageable.getPageNumber());
        return new PageImpl<>(pageContent, pageable, ingredientVOS.size());
    }

}

测试:

/**
 * @Author: Be_insighted
 * Description:
 * @date Create on 2020/7/10 9:38
 **/
@Slf4j
public class TestConvertList2PageObject {
    public static void main(String[] args) {
        List<User> users = new ArrayList<>();
        User user0 = new User().setAge(60).setNickname("稀烂的").setUsername("好美国儿童");
        User user1 = new User().setAge(60).setNickname("基辛格").setUsername("基佬");
        User user2 = new User().setAge(60).setNickname("奥巴驴").setUsername("核平");
        User user3 = new User().setAge(60).setNickname("特朗普").setUsername("狗屎");
        users.add(user0);
        users.add(user1);
        users.add(user2);
        users.add(user3);
        Page<User> ret = ConvertList2PageVOUtil.convertList2PageVO(users, 1, 2);
        log.info("测试0:{}===={}===={}===={}",    ret.getContent(),ret.getTotalElements(),ret.getTotalPages(),ret.getNumberOfElements());
        int page = 1;
        int size = 2;
        Pageable pageable = new PageRequest(page - 1, size);
        Page<User> ret1 = ConvertList2PageVOUtil.convertList2PageVO(users, pageable);
        log.info("测试1:{}===={}===={}===={}",   ret1.getContent(),ret1.getTotalElements(),ret1.getTotalPages(),ret.getNumberOfElements());

    }
}

第一页内容

第二页内容

 

 

 

 

 

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页