Languages
[Edit]
EN

Java - calculate number of pages from size of page and total number of items

6 points
Created by:
Violet-Hoffman
652

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 (totalCount variable),
  • the maximal size of the page is 10 items (pageSize variable),

So:

  • page 1 should have 10 items
  • page 2 should have 10 items
  • page 3 should have  1 item

so we have 3 pages.

 

See also

  1. JavaScript - calculate number of pages from size of page and total number of items 

Alternative titles

  1. Java - the simplest formula to calculate page count
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join