1. 程式人生 > 實用技巧 >javaweb資料分頁

javaweb資料分頁

    public List<Record>  getPageList(List<Record> list, Integer pageSize, Integer pageNum){
        if (list.size() <=pageSize){
            return list;
        }else{
            if(list.size()%pageSize==0){
                return list.subList((pageNum-1)*pageSize,pageNum*pageSize);
            }else{
                int nums = list.size() / pageSize;
                if(pageNum==nums+1){//最後一頁
                    return list.subList((pageNum-1)*pageSize,list.size());
                }else{
                    return list.subList((pageNum-1)*pageSize,pageNum*pageSize);
                }
            }
        }
    }


```//分頁類
package com.hiwan.uulife.common.utils;

import org.apache.commons.lang.StringUtils;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author wsl
 * @Description: TODO
 * @date 2017/10/31
 */
public class RAMPageUtil {
    /**
     * 根據傳入的陣列和頁碼返回分頁後的陣列
     * @param original 全量資料的陣列
     * @param pageNum 頁碼
     * @param pageSize 每頁資料條數
     * @param <T>
     * @return 返回分頁後的對應頁碼頁面的資料
     */
    public static <T> T[] page(T[] original, int pageNum, int pageSize) {
        if(null==original || original.length == 0) return (T[]) Array.newInstance(original.getClass().getComponentType(), 0);
        if (pageNum <= 0) pageNum = 1;
        int from = (pageNum - 1) * pageSize;
        int to = pageNum * pageSize;
        if(to > original.length) to = original.length;
        if(from>=original.length || to <= from) return (T[]) Array.newInstance(original.getClass().getComponentType(), 0);
        return Arrays.copyOfRange(original, from, to);
    }


    public static <T> List<T> page(List<T> original, int pageNum, int pageSize){
        List list = new ArrayList<T>();
        Collections.addAll(list,page(original.toArray(),pageNum,pageSize));
        return list;
    }

    public static int totalPage (int pageSize,int pageNum){
        if (pageSize==0) return 0;
        if (pageSize / pageNum == 0) return 1;
        if (pageSize % pageNum == 0) return pageNum / pageNum;
        return pageNum / pageNum + 1;
    }

}