This post will discuss how to partition a list into multiple sublists in Java using Java Collections, Guava library, and Apache Common Collections.

In the previous post, we have discussed how to partition a list into two sublists in Java. This post will discuss how to partition a list into multiple sublists.

1. Naive solution

A naive solution is to create m empty lists and process each element of the original list, and add it to the corresponding sublist based on its position in the original list, as shown below:

Download  Run Code

2. Using List.subList() method

List interface provides the subList() method that returns a sublist between the specified indexes, backed by the list. We can use this method to partition our list into multiple sublists, but since the returned sublists are just views of the original list, we can construct new lists from the returned views, as shown below:

Download  Run Code

3. Using Guava Library

With the Guava library, we can use the Lists.partition() method that partitions the list into consecutive sublists, each of the specified size.

Download Code

 
Guava’s Iterables class contains a static utility method partition(Iterable<T>, int) that divides an iterable into unmodifiable sublists of the given size. We can use this method to partition our list into multiple sublists, but since the returned sublists are unmodifiable, we can construct new mutable lists from the returned sublists.

Download Code

4. Using Apache Commons Collections

Apache Commons Collections also provides the ListUtils.partition() method that has exact functionality as Guava’s Lists.partition() method.

Download Code

That’s all about partitioning a list into multiple sublists in Java.