1. Introduction
In many scenarios, particularly in web applications, it’s essential to implement pagination to handle large sets of data effectively. In Java, we can achieve list pagination by using subList method available in the List interface. This method returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive.
2. Program Steps
1. Import the necessary libraries.
2. Create a list of elements.
3. Define the page size (number of elements per page).
4. Calculate the total number of pages.
5. Loop through each page and display the elements of each page using the subList method.
3. Code Program
// Step 1: Import the necessary libraries
import java.util.ArrayList;
import java.util.List;
public class ListPagination {
public static void main(String[] args) {
// Step 2: Create a list of elements
List<String> items = new ArrayList<>();
for (int i = 1; i <= 25; i++) {
items.add("Item " + i);
}
// Step 3: Define the page size (number of elements per page)
int pageSize = 5;
// Step 4: Calculate the total number of pages
int totalPages = (int) Math.ceil((double) items.size() / pageSize);
// Step 5: Loop through each page and display the elements of each page using the subList method
for (int i = 0; i < totalPages; i++) {
int fromIndex = i * pageSize;
int toIndex = Math.min(fromIndex + pageSize, items.size());
List<String> page = items.subList(fromIndex, toIndex);
System.out.println("Page " + (i + 1) + ": " + page);
}
}
}
Output:
Page 1: [Item 1, Item 2, Item 3, Item 4, Item 5] Page 2: [Item 6, Item 7, Item 8, Item 9, Item 10] Page 3: [Item 11, Item 12, Item 13, Item 14, Item 15] Page 4: [Item 16, Item 17, Item 18, Item 19, Item 20] Page 5: [Item 21, Item 22, Item 23, Item 24, Item 25]
4. Step By Step Explanation
Step 1: Import the ArrayList and List classes from the java.util package.
Step 2: Create and initialize a List of 25 items.
Step 3: Define the page size as the number of elements that each page will contain.
Step 4: Calculate the total number of pages required to display all elements given the page size.
Step 5: Loop through each page and, for every page, calculate the fromIndex and toIndex to get a subList representing the current page. Then, display the elements of each page.