jorge-aranda
3/11/2018 - 1:06 AM

ListUtils with a list paginator

ListUtils with a list paginator


package ***;

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

public class ListUtils {

    private ListUtils() {
        // no instanciable
    }

     public static <T> List<T> paginateList(
            final List<T> sourceList, final Integer max,
            final Integer offset) {

         final List<T> filteredItems;

         if (sourceList != null || !sourceList.isEmpty()) {

             final int fromIndex =
                     calculateFromIndex(offset, sourceList.size());
             final int toIndex =
                     calculateToIndex(sourceList, max, fromIndex);

             // Getting filtered elements
             filteredItems = sourceList.subList(fromIndex, toIndex);

         } else if (sourceList != null) {
             filteredItems = new ArrayList<T>();
         } else {
             filteredItems = null;
         }

         return filteredItems;
    }

    private static int calculateFromIndex(final int offset, final int count) {
        final int fromIndex;

        if (offset > 0) {
            if (offset < count) {
                fromIndex = offset;
            } else {
                fromIndex = count;
            }
        } else {
            fromIndex = 0;
        }
        return fromIndex;
    }

    private static <T> int calculateToIndex(
                                 final List<? extends T> sourceList,
                                 final Integer max, final int fromIndex) {
        final int toIndex;

        if (max != null) {
            final int endCalculatedPosition = max + fromIndex;

            if (endCalculatedPosition < sourceList.size()) {
                toIndex = endCalculatedPosition;
            } else {
                toIndex = sourceList.size();
            }
        } else {
            toIndex = sourceList.size();
        }

        return toIndex > fromIndex ? toIndex : fromIndex;
    }


}