Splitting a list in Java

How to split a list into multiple parts of the same size seems like a common question (1,2). Most answers either point to adding an additional library such as Guava or Apache Commons.

As an experiment I’ve tried a differend approach. Splitting a list by using recursion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public static <T> List<List<T>> split(List<T> source, Integer partitionSize) {
if(partitionSize < 1){
throw new IllegalArgumentException("partitionSize must be at least 1");
}
if(source.isEmpty()){
return new ArrayList<>();
}
int currentChunkSize = Math.min(partitionSize, source.size());
List<T> head = source.subList(0, currentChunkSize);
List<T> tail = source.subList(currentChunkSize, source.size());
List<List<T>> result = split(tail, partitionSize);
result.add(0, head);
return result;
}

Testing the code seems to generate a successful output:

1
2
3
4
5
6
7
8
9
@Test
public void splitTest() {
List<String> source = Arrays.asList("1", "2", "3", "4", "5");
List<List<String>> result = split(source, 3);
assertEquals(Arrays.asList("1", "2", "3"), result.get(0));
assertEquals(Arrays.asList("4", "5"), result.get(1));
}

However there is a word of warning! Java does not support Tail recursion optimization. So depending on your JVMs stacksize you may receive a StackOverflowError if you split a collection in more then 7000 parts.