Paginate the list collection and display the data on the page

Tools

工具类代码:

public class PageUtil {

    /**
     * 开始分页
     * @param list
     * @param pageNum 页码
     * @param pageSize 每页多少条数据
     * @return
     */
    public static List startPage(List list, Integer pageNum,
                                 Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }
        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }
        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引
        if (pageNum > pageCount){
            return null;
        }
        if (pageNum != pageCount) {
            System.out.println("pageNum====>"+pageNum);
            fromIndex = (pageNum - 1) * pageSize;
            System.out.println("fromindex===>"+fromIndex);
            toIndex = fromIndex + pageSize;
        } else {
            System.out.println("from====>"+fromIndex);
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }
        List pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }
}

在项目中的用法

从数据库中查出的数据集合:noGroup
List<Students> noGroup = studentsService.queryStudentNotInGroup(campusId, phone);
调用工具类的方法:
List<Students> page = PageUtil.startPage(noGroup,pageNum,pageSize);
总条数:
Integer count = noGroup.size();
总页码:
Integer totalPage = count % 10 == 0 ? count / 10 : count / 10 + 1;
map.put("totalPage", totalPage);
map.put("page", page);

It has been tested and works. I hope it can help you.

**Modify it: If there is too much data, the if (pageNum != pageCount) line will report an error, and the test will! =Modify to! equals---------> if (!pageNum.equals(pageCount)) **

Modification: If the incoming page number is greater than the total page number, a null pointer exception will be reported, so a judgment is added:
if (pageNum > pageCount) { return null; }

Note: This paging tool class is only suitable for small amounts of data. For millions of data, the response time will be very long. The reason is that all the data is first found in the collection, and then all the data is paged. If For millions of data, querying takes time, so the response is very slow. A better method is still being considered. If you have a better method, please provide it.

Supongo que te gusta

Origin blog.csdn.net/weixin_44021888/article/details/102715680
Recomendado
Clasificación