Split a List into two Sublists in Java

In this post, we will see how to split a List into two Sublists in Java using Java Collections, Java 8, Guava library and Apache Common Collections.

 

1. Naive

Naive solution would to create two new empty lists and assign elements from first half of the original list to the first list and elements from second half of the original list to the second list.

 

Download   Run Code

 

2. List.subList()

This is recommended approach in Java SE where we use List.subList() method that returns a view of this list between the specified indexes. Since the returned list is backed by this list, we can construct a new List from the returned view as shown below:

Download   Run Code

 

3. Java 8 Stream API

 

3.1. Collectors partitioningBy

We can use Collectors.partitioningBy() to split the list into two sublists in Java 8 as shown below

Download   Run Code

Similar to Collectors.partitioningBy(), we can use Collectors.groupingBy() to split the list into two sublists as shown below:

Download   Run Code

 

3.2. List.subList()

This is just an alternative way in Java 8 to split the list using list.subList() method discussed earlier.

Download   Run Code

 

4. Guava

With Guava library, we can use Lists.partition() method that splits the list into consecutive sublists, each of the specified size. In order to split the list into two sublists, we can pass the size that is equal to half the size of our list.

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 split our list into two sublists, but since the returned sublists are unmodifiable, we can construct new mutable Lists from the returned sublists as shown below:

Download   Run Code

 

5. Apache Commons Collections

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

Download

 
Related Article: Partition a List into Multiple Sublists in Java

 
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