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.
Discover more from GhostProgrammer - Jeff Miller
Subscribe to get the latest posts sent to your email.