Java List Sub List splitListToSubLists(List parentList, int subListSize)

Here you can find the source of splitListToSubLists(List parentList, int subListSize)

Description

split List To Sub Lists

License

Apache License

Declaration

public static <T> List<List<T>> splitListToSubLists(List<T> parentList, int subListSize) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.util.ArrayList;

import java.util.Collection;

import java.util.List;

public class Main {
    public static <T> List<List<T>> splitListToSubLists(List<T> parentList, int subListSize) {
        List<List<T>> subLists = new ArrayList<List<T>>();
        if (subListSize > parentList.size()) {
            subLists.add(parentList);/*www  . j av a 2 s. c  o  m*/
        } else {
            int remainingElements = parentList.size();
            int startIndex = 0;
            int endIndex = subListSize;
            do {
                List<T> subList = parentList.subList(startIndex, endIndex);
                subLists.add(subList);
                startIndex = endIndex;
                if (remainingElements - subListSize >= subListSize) {
                    endIndex = startIndex + subListSize;
                } else {
                    endIndex = startIndex + remainingElements - subList.size();
                }
                remainingElements -= subList.size();
            } while (remainingElements > 0);

        }
        return subLists;
    }

    public static int size(Collection<?> col) {
        return col == null ? 0 : col.size();
    }
}

Related

  1. lastIndexOfSubList(final List list0, final List list1)
  2. slice(List stringList, int subListSize)
  3. split(List from, int subListSize)
  4. splitIntoSubListsByNumber(final List list, final int numberOfSublists)
  5. splitList(List list, int subListNumber)
  6. startsWith(final List list, final List subList)
  7. sub(List l, int index)
  8. subArray(List listA, List listB)
  9. subList(final Iterable

    parent, final Iterable child)