How to implement pagination on a list?

I've solved this before. I made a static getPages method that breaks a generic collection into a list of pages (which are also lists). I've provided the code below.

public static <T> List<List<T>> getPages(Collection<T> c, Integer pageSize) {
    if (c == null)
        return Collections.emptyList();
    List<T> list = new ArrayList<T>(c);
    if (pageSize == null || pageSize <= 0 || pageSize > list.size())
        pageSize = list.size();
    int numPages = (int) Math.ceil((double)list.size() / (double)pageSize);
    List<List<T>> pages = new ArrayList<List<T>>(numPages);
    for (int pageNum = 0; pageNum < numPages;)
        pages.add(list.subList(pageNum * pageSize, Math.min(++pageNum * pageSize, list.size())));
    return pages;
}

Minor optimization, if you don't really want to create any new list at all.

/**
 * returns a view (not a new list) of the sourceList for the 
 * range based on page and pageSize
 * @param sourceList
 * @param page, page number should start from 1
 * @param pageSize
 * @return
 * custom error can be given instead of returning emptyList
 */
public static <T> List<T> getPage(List<T> sourceList, int page, int pageSize) {
    if(pageSize <= 0 || page <= 0) {
        throw new IllegalArgumentException("invalid page size: " + pageSize);
    }
    
    int fromIndex = (page - 1) * pageSize;
    if(sourceList == null || sourceList.size() <= fromIndex){
        return Collections.emptyList();
    }
    
    // toIndex exclusive
    return sourceList.subList(fromIndex, Math.min(fromIndex + pageSize, sourceList.size()));
}

Tags:

Java

Paging