Partition a List into Multiple Sublists in Java

In this post, we will see 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. In this post, we will see how to partition a List into multiple sublists.

 

1. Naive

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

 

Download   Run Code

 

2. List.subList()

List interface provides subList() method that returns a sublist between the specified indexes which is 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. Guava

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

Download   Run 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   Run Code

 

4. Apache Commons Collections

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

Download

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz