Fri. Mar 29th, 2024
Pick a page

Ever have a list, that you need to paginate through? I certainly have, I created a simple method to ListUtils to make it easier.

 /**
     *  Performs pagination on the List,  returning the indicated page of elements, or an empty ist.
     * @param list List to paginate
     * @param pageSize Number of elements per page
     * @param page The Page to return
     * @param <E> Type of Elements
     * @return Empty list if no matching page, or List containing the page's elements.
     */
    public static <E> List<E> page( List<E> list, int pageSize, int page) {
        List<E> safe = ListUtils.safe(list);

        if(pageSize > 0 && page >= 0 && safe.size() > 0) {
            int startIndex = pageSize * (page - 1);
            int endIndex = startIndex + pageSize;
            if(startIndex > safe.size()) {
                return Collections.EMPTY_LIST;
            }

            if(endIndex > safe.size()) {
                endIndex = safe.size() - 1;
            }

            return safe.subList(startIndex,endIndex);
        }

        return Collections.EMPTY_LIST;
    }

Several things had to be taken into consideration. First off calling subList() will throw an exception if you go beyond the index, we have to handle it. So we add a check to reset it.

if(endIndex > safe.size()) {
    endIndex = safe.size() - 1;
}

We also need to check to make sure the startIndex does not exceed the index.

if(startIndex > safe.size()) {
    return Collections.EMPTY_LIST;
}

Once you exceed the end of the list, we return an empty lists.

By Jeffery Miller

I am known for being able to quickly decipher difficult problems to assist development teams in producing a solution. I have been called upon to be the Team Lead for multiple large-scale projects. I have a keen interest in learning new technologies, always ready for a new challenge.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d