java list实现分页

   /**
     * list分页
     * @param list
     * @param pageNo 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static <T> List<T> splitList(List<T> list, int pageNo, int pageSize) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        int totalCount = list.size();
        pageNo = pageNo - 1;
        int fromIndex = pageNo * pageSize;
        // 分页不能大于总数
        if(fromIndex >= totalCount) {
            return null;
        }
        int toIndex = ((pageNo + 1) * pageSize);
        if (toIndex > totalCount) {
            toIndex = totalCount;
        }
        return list.subList(fromIndex, toIndex);
    }

    /**
     * list分页
     * @param list
     * @param page
     * @return
     */
    public static <T> List<T> splitList(List<T> list, Page page) {
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        int totalCount = list.size();
        int fromIndex = page.getBegin();
        // 分页不能大于总数
        if(fromIndex >= totalCount) {
            return null;
        }
        int pageNo = (int)Math.floor((double)page.getBegin() * 1.0D / (double)page.getLength()) + 1;
        int toIndex = pageNo * page.getLength();
        if (toIndex > totalCount) {
            toIndex = totalCount;
        }
        return list.subList(fromIndex, toIndex);
    }

 

posted @ 2021-01-07 15:26  二次元的程序猿  阅读(1280)  评论(0编辑  收藏  举报