EN
Java - calculate number of pages from size of page and total number of items
6
points
In this article, we're going to have a look at how in Java, calculate a number of pages when we know:
- maximal size of the page,
- a total number of items.
Quick solution:
long pageSize = 10;
long totalCount = 21;
long pagesCount = totalCount < pageSize ? 1 : (long) Math.ceil((double) totalCount / pageSize);
Practical example
Simple example:
public class PaginationUtils {
/**
* Calculates number of pages for given page size and total number of items.
*
* Assumption:
* we suppose that if we have 0 items we want 1 empty page
*/
public static long calculatePagesCount(long pageSize, long totalCount) {
return totalCount < pageSize ? 1 : (long) Math.ceil((double) totalCount / (double) pageSize);
}
}
Usage example:
public class Program {
public static void main(String[] args) {
long pageSize = 10;
long totalCount = 21;
long pagesCount = PaginationUtils.calculatePagesCount(pageSize, totalCount);
System.out.println("pagesCount=" + pagesCount); // pagesCount=3
}
}
Output:
pagesCount=3
The above logic result explanation:
- the total number of items is
21(totalCountvariable),- the maximal size of the page is
10items (pageSizevariable),So:
- page
1should have10items- page
2should have10items- page
3should have1itemso we have
3pages.