This post will discuss how to split a list into two sublists using Java Collections, Java 8, Guava library, and Apache Common Collections.

1. Naive solution

A naive solution is to create two new empty lists and assign elements from the first half of the original list to the first list and elements from the second half of the original list to the second list.

Download  Run Code

2. Using List.subList() method

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

Download  Run Code

3. Using Java 8 Stream

⮚ Collectors partitioningBy

We can use Collectors.partitioningBy() to split the list into two sublists in Java 8 and above, 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

List.subList()

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

Download  Run Code

4. Using Guava Library

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

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

5. Using Apache Commons Collections

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

Download Code

That’s all about splitting a list into two sublists in Java.

 
Related Article:

Partition a list into multiple sublists in Java