Index-Based Pagination for Java Collections and JavaScript Arrays

Implementing pagination by calculating array indices is a practical approach when dealing with in-memory data that hasn't been persisted to a database. This techniqeu is particularly valuable for frontand features requiring search and pagination capabilities on temporarily stored selections.

Java List Pagination

The following generic utility method slices any List implementation based on page number and size parameters:

import java.util.List;
import java.util.ArrayList;

public class CollectionPaginator {
    
    /**
     * Extracts a page of elements from a List using index-based calculation
     * @param source The original data list
     * @param pageNumber The requested page (1-based)
     * @param pageSize Number of elements per page
     * @return A new list containing the paginated results
     */
    public static <T> List<T> extractPage(List<T> source, int pageNumber, int pageSize) {
        if (source == null || source.isEmpty() || pageSize <= 0) {
            return new ArrayList<>();
        }
        
        int total = source.size();
        int startIdx = (pageNumber - 1) * pageSize;
        
        if (startIdx >= total) {
            return new ArrayList<>();
        }
        
        int endIdx = Math.min(startIdx + pageSize, total);
        return new ArrayList<>(source.subList(startIdx, endIdx));
    }
}

JavaScript Array Pagination

A parallel implemantation for JavaScript arrays using the native slice method:

/**
 * Paginates an array by calculating start and end indices
 * @param {Array<*>} dataArray - Source array to paginate
 * @param {number} currentPage - Page number to retrieve (starts at 1)
 * @param {number} itemsPerPage - How many items each page contains
 * @returns {Array<*>} New array with paginated elements
 */
function slicePage(dataArray, currentPage, itemsPerPage) {
    if (!Array.isArray(dataArray) || dataArray.length === 0 || itemsPerPage <= 0) {
        return [];
    }
    
    const startPosition = (currentPage - 1) * itemsPerPage;
    
    if (startPosition >= dataArray.length) {
        return [];
    }
    
    const endPosition = Math.min(startPosition + itemsPerPage, dataArray.length);
    return dataArray.slice(startPosition, endPosition);
}

Both functions validate input parameters and return empty collections when the requested page exceeds available data. This design eliminates the need for null checks in calling code and provides consistent behavior across edge cases.

Tags: java javascript Pagination in-memory-pagination array-manipulation

Posted on Sun, 23 Aug 2026 16:36:06 +0000 by MCP