java8 stream对list进行分页

java8 stream对list进行分页

1、使用java8 stream的方式进list的分页

下面是代码片段。

// pageNum 页码数   pageSize 页容量 
List pageList = list.stream().sorted().skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());

接下来使用pagehelper进行包装成工具

/*
     * Discreption: java8 手动对list分页
     * @param: [list, pageNum, pageSize]
     * @return: com.github.pagehelper.PageInfo
     * @author: wangm
     * @date: 2020/5/27 4:30 PM
     */
    public static  PageInfo list2PageInfo( Integer pageNum, Integer pageSize,List list) {
        //java8 stream实现list分页
        List pageList = list.stream().sorted().skip((pageNum - 1) * pageSize)
                .limit(pageSize)
                .collect(Collectors.toList());
        PageInfo pageInfo = new PageInfo(pageList);
        //获取PageInfo其他参数
        pageInfo.setTotal(list.size());
        int endRow = pageInfo.getEndRow() == 0 ? 0 : (pageNum - 1) * pageSize + pageInfo.getEndRow() + 1;
        pageInfo.setEndRow(endRow);
        boolean hasNextPage = list.size() <= pageSize * pageNum ? false : true;
        pageInfo.setHasNextPage(hasNextPage);
        boolean hasPreviousPage = pageNum == 1 ? false : true;
        pageInfo.setHasPreviousPage(hasPreviousPage);
        pageInfo.setIsFirstPage(!hasPreviousPage);
        boolean isLastPage = (list.size() > pageSize * (pageNum - 1) && list.size() <= pageSize * pageNum) ? true : false;
        pageInfo.setIsLastPage(isLastPage);
        int pages = list.size() % pageSize == 0 ? list.size() / pageSize : (list.size() / pageSize) + 1;
        pageInfo.setNavigateLastPage(pages);
        int[] navigatePageNums = new int[pages];
        for (int i = 1; i < pages; i++) {
            navigatePageNums[i - 1] = i;
        }
        pageInfo.setNavigatepageNums(navigatePageNums);
        int nextPage = pageNum < pages ? pageNum + 1 : 0;
        pageInfo.setNextPage(nextPage);
        pageInfo.setPageNum(pageNum);
        pageInfo.setPageSize(pageSize);
        pageInfo.setPages(pages);
        pageInfo.setPrePage(pageNum - 1);
        pageInfo.setSize(pageInfo.getList().size());
        int starRow = list.size() < pageSize * pageNum ? 1 + pageSize * (pageNum - 1) : 0;
        pageInfo.setStartRow(starRow);
        return pageInfo;
    }

你可能感兴趣的:(java8,stream,分页,java,stream,lambda)