Java实现手动分页

1.手动分页工具类

/*
 *
 *      Copyright (c) 2018-2025, tuanzi All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the tuanzi developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: tuanzi (1766285184@qq.com)
 *
 */

package com.jlq.mes.biz.utils;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述: 分页工具类
 *
 * @author tuanzi
 * @Date 2022/5/20 1:50 下午
 */
public class PageUtils {

    /**
     * 手动分页
     * @param data     要分页的集合数据
     * @param pageSize 条数
     * @param pageNum  页数
     * @param <T>      <T>
     * @return List<T>
     */
    public static <T> List<T> getManualPaging(List<T> data, int pageSize, int pageNum) {
        int startNum = (pageNum - 1) * pageSize + 1;                     //起始截取数据位置
        if (startNum > data.size()) {
            return null;
        }
        List<T> res = new ArrayList<>();
        int rum = data.size() - startNum;
        if (rum < 0) {
            return null;
        }
        if (rum == 0) {                                               //说明正好是最后一个了
            int index = data.size() - 1;
            res.add(data.get(index));
            return res;
        }
        if (rum / pageSize >= 1) {                                    //剩下的数据还够1页,返回整页的数据
            for (int i = startNum; i < startNum + pageSize; i++) {          //截取从startNum开始的数据
                res.add(data.get(i - 1));
            }
            return res;
        } else if ((rum / pageSize == 0) && rum > 0) {                 //不够一页,直接返回剩下数据
            for (int j = startNum; j <= data.size(); j++) {
                res.add(data.get(j - 1));
            }
            return res;
        } else {
            return null;
        }
    }


}

2.使用方法

 List<User> manualPaging = PageUtils.getManualPaging(userList, param.getPageSize(), param.getPageNum());

param 为实体对象
第一个参数:userList 要分页的集合数据
第二个参数:PageSize 每页条数
第三个参数:PageNum 第几页

Q.E.D.