This post will discuss how to split a list into sub-lists of size n in Java. Note that the final list may be smaller than n depending upon the size of the list.

1. Using Guava

With the Guava library, you can use the Lists.partition() method to partition a list into consecutive sublists, each of the specified size. Following is a simple example demonstrating the usage of this method:

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

2. Using Apache Commons Collections

Similar to the Guava’s Lists.partition() method, Apache Commons Collections ListUtils class offers partition() method offering the similar functionality.

Download Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

3. Using List.subList() method

If you don’t prefer third-party libraries, you can write your own routine for this task. The following solutions use a regular for-loop to iterate the list and the List.subList() method to get the partition between starting and ending index.

Download  Run Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

 
This is equivalent to the following using Java 8 Stream API:

Download  Run Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

 
Finally, with Java 9 you can simplify the code using the IntStream.iterate() method which takes a predicate.

Download  Run Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

4. Using Collectors.groupingBy() method

There are more ways to split a list in Java using Stream API. The following solution uses Collectors.groupingBy() to perform the equivalent of a “group by” operation on the list elements. It groups the elements according to a classification function and returns the results in a map.

Download  Run Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

 
The code can be simplified using a mutable counter like AtomicInteger class:

Download  Run Code

Output:

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]

That’s all about splitting a list into sub-lists of size n in Java.