JavaTechnology

How to Partition List in Multiple Sublists in Java

A quick guide on Partition a List in Java. We will learn ways to split a list into multiple sublists of specified size.

Overview

Partitioning a List means dividing a list into a number of sublists also called a partitions, where each partition, contains a specific number of elements while the last partition can contain less elements.

Many a times we need to split a list in equal partitions or based on the elements of the list. We use partitions mainly for multi-threading where we want to divid work equally between a number of worker threads, or to process a large list into small batches, etc. Till this point, Java doesn’t have support to partition lists. Hence, Guava and Apache Commons Collections libraries are the most popular ones. However, we can write our own partition method using plain java.

In this tutorial, we will cover examples of dividing list into multiple sublists of given size by using guava, apache commons collections, and plain Java.

Partition using Guava

Make sure you have Guava library in your classpath. You can use guava dependency in your Maven or Gradle builds.

Note: All partitions created by Guava are just views on the original list. Thus, any modifications to the list will reflect in the partitions as well.

List Partition Using Guava

Guava provides a partition method which accepts the list to be partitioned and size of each partition.

List<Integer> list = IntStream.rangeClosed(1, 21).boxed().collect(Collectors.toList());

List<List<Integer>> partitions = Lists.partition(list, 4);

partitions.forEach(System.out::println);

In the above example, we are creating a list of integers containing 21 numbers, starting from 1 to 21. We use Guava to partition list of size 4. Next, is the output that we get.

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]
[17, 18, 19, 20]
[21]

As expected we got 5+1 partitions, where 5 partitions are of the given size and last one has the remaining elements.

As stated above, all partitions are just a views on the original list. To test that, let’s remove an element from the list and print the partitions again.

list.remove(2);
partitions.forEach(System.out::println);

As expected the output has only 5 partitions and the element at the 2nd index position is missing.

[1, 2, 4, 5]
[6, 7, 8, 9]
[10, 11, 12, 13]
[14, 15, 16, 17]
[18, 19, 20, 21]

Collection Partition using Guava

Similar to List, we can use Guava partition a Collection using Iterables.partition method.

Collection<Integer> list = IntStream.rangeClosed(1, 21).boxed().collect(Collectors.toList());
Iterable<List<Integer>> partitions = Iterables.partition(list, 4);

Collections Padded Partition using Guava

With partition the last sublist can have less numbers. If we want to create collection partitions of exact same size we can use the padded partition alternative.

Collection<Integer> list = IntStream.rangeClosed(1, 21).boxed().collect(Collectors.toList());

Iterable<List<Integer>> partitions = Iterables.paddedPartition(list, 4);

partitions.forEach(System.out::println);

The output we get is

[1, 2, 3, 4]
[5, 6, 7, 8]
[9, 10, 11, 12]
[13, 14, 15, 16]
[17, 18, 19, 20]
[21, null, null, null]

Notice that, even the last sublist has 4 elements where rest of the elements are padded using null.

Partition using Apache Commons Collections

Similarly, Apache Commons Collections also provide a way to partition Lists.

List<Integer> list = IntStream.rangeClosed(1, 21).boxed().collect(Collectors.toList());
List<List<Integer>> partitions = ListUtils.partition(list, 4);

Similar to the Guava, the partitions created by Apache Commons Collections library are views of the original list.

Partition Using Plain Java

Both of the above examples, involves using a third party library. However, we can write our own partition method in plain Java.

Next is an Example of Creating sublists from List in Plain Java using List.sublist.

public static<T> List<List<T>> partition(List<T> list, int size) {
    List<List<T>> partitions = new ArrayList<>();

    if (list.size() == 0) {
        return partitions;
    }

    int length = list.size();

    int numOfPartitions = length / size + ((length % size == 0) ? 0 : 1);

    for (int i = 0; i < numOfPartitions; i++) {
        int from = i * size;
        int to = Math.min((i * size + size), length);
        partitions.add(list.subList(from, to));
    }
    
    return partitions;
}

The arguments to this methods are the list to be partitioned and the expected size of partition.

First, we calculate the number of resulting partitions. Next, for each of the partition we are use sublist method on java list object by passing from index and to index.
The partitions we create here are actual lists and not views of the original list. Hence modifications to the original list, will not be reflected into the partitions.

Summary

In this tutorial we leaned How to Partition a List in Java. We have covered three examples: partition using guava library, partition using apache commons collections library, and finally with writing our own partition method using plain Java. For more on Java visit Introduction to Java.