PageUtils.java 2.33 KB
Newer Older
刘基明's avatar
刘基明 committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
package com.tanpu.community.util;

import com.tanpu.community.api.beans.req.page.Page;
import com.tanpu.community.api.beans.req.page.Pageable;
import org.springframework.util.CollectionUtils;

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

/**
 * @author: zhoupeng
 * @email: zhoupeng@wealthgrow.cn
 */
public class PageUtils {
    public static <T> Page<T> page(Pageable pageable, List<T> list) {
        if (CollectionUtils.isEmpty(list)) {
刘基明's avatar
刘基明 committed
17 18 19
            if(pageable==null){
                return new Page<T>(1,0, (long)list.size(),1, list);
            }
刘基明's avatar
刘基明 committed
20 21
            return new Page<>(pageable, 0L, new ArrayList<>());
        } else {
刘基明's avatar
刘基明 committed
22
            if(pageable==null){
刘基明's avatar
刘基明 committed
23
                return new Page<T>(1,list.size(), (long)list.size(),1, list);
刘基明's avatar
刘基明 committed
24
            }
刘基明's avatar
刘基明 committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40

            // 记录总数
            Integer count = list.size();
            // 页数
            int pageCount;
            if (count % pageable.getPageSize() == 0) {
                pageCount = count / pageable.getPageSize();
            } else {
                pageCount = count / pageable.getPageSize() + 1;
            }
            // 开始索引
            int fromIndex;
            // 结束索引
            int toIndex;

            // 防止索引越界
刘基明's avatar
刘基明 committed
41
            if (Integer.valueOf(0).equals(pageable.getPageNumber())) {
刘基明's avatar
刘基明 committed
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
                pageable.setPageNumber(1);
            }

            if (!pageable.getPageNumber().equals(pageCount)) {
                fromIndex = (pageable.getPageNumber() - 1) * pageable.getPageSize();
                toIndex = fromIndex + pageable.getPageSize();
            } else {
                fromIndex = (pageable.getPageNumber() - 1) * pageable.getPageSize();
                toIndex = count;
            }
            if (pageable.getPageSize() * (pageable.getPageNumber() - 1) >= list.size()) {
                return new Page<>(pageable, 0L, new ArrayList<>());
            } else {
                Page<T> tPage = new Page<>(pageable, (long) list.size(), new ArrayList<>(list).subList(fromIndex, toIndex));

                int totalPage = list.size() / pageable.getPageSize();
                if (list.size() % pageable.getPageSize() == 0) {
                    tPage.setTotalPages(totalPage);
                } else {
                    tPage.setTotalPages(totalPage + 1);
                }
                return tPage;
            }
        }
    }
}