How to implement pagination in Java lists?
In Java, we can use the List.subList() method to achieve pagination of a list. This method allows us to retrieve a specific range of elements from the original list, thereby enabling pagination.
Here is a simple example code demonstrating how to implement pagination for a Java list.
import java.util.ArrayList;
import java.util.List;
public class ListPaginationExample {
public static void main(String[] args) {
List<String> originalList = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
originalList.add("Item " + i);
}
int pageSize = 10;
int pageNumber = 2;
int startIndex = (pageNumber - 1) * pageSize;
int endIndex = Math.min(startIndex + pageSize, originalList.size());
List<String> paginatedList = originalList.subList(startIndex, endIndex);
for (String item : paginatedList) {
System.out.println(item);
}
}
}
In the example above, we first created a originalList containing 100 elements. Then we defined the number of elements to display per page, pageSize, and the page number to display, pageNumber. Next, we calculated the starting index of the sublist startIndex and the ending index endIndex, and then used the List.subList() method to retrieve the sublist. Finally, we iterated through the paginated list and printed each element.
When we run the above code, it will display the content of the second page, which includes elements 11 to 20. You can adjust the pageSize and pageNumber as needed to achieve different pagination effects.