How to split array list into equal parts?

generic function :

public static <T> ArrayList<T[]> chunks(ArrayList<T> bigList,int n){
    ArrayList<T[]> chunks = new ArrayList<T[]>();

    for (int i = 0; i < bigList.size(); i += n) {
        T[] chunk = (T[])bigList.subList(i, Math.min(bigList.size(), i + n)).toArray();         
        chunks.add(chunk);
    }

    return chunks;
}

enjoy it~ :)


Java 8 (not that it has advantages):

List<String> list = new ArrayList<>();
Collections.addAll(list,  "a","b","c","b","c","a","c","a","b");

Grouping size:

final int G = 3;
final int NG = (list.size() + G - 1) / G;

In old style:

List<List<String>> result = new ArrayList(NG);
IntStream.range(0, list.size())
    .forEach(i -> {
        if (i % G == 0) {
            result.add(i/G, new ArrayList<>());
        }
        result.get(i/G).add(list.get(i));
    });

In new style:

List<List<String>> result = IntStream.range(0, NG)
    .mapToObj(i -> list.subList(G * i, Math.min(G * i + G, list.size())))
    .collect(Collectors.toList());

Thanks to @StuartMarks for the forgotten toList.


If you're constrained by PL/SQL in limits then you want to know how to split a list into chunks of size <=n, where n is the limit. This is a much simpler problem as it does not require knowing the size of the list in advance.

Pseudocode:

for (int n=0; n<list.size(); n+=limit)
{
    chunkSize = min(list.size,n+limit);
    chunk     = list.sublist(n,chunkSize);
    // do something with chunk
}

This should give you all your parts :

int partitionSize = 1000;
List<List<Integer>> partitions = new LinkedList<List<Integer>>();
for (int i = 0; i < originalList.size(); i += partitionSize) {
    partitions.add(originalList.subList(i,
            Math.min(i + partitionSize, originalList.size())));
}