how-to · java · collections

How-to split (partition) Collection in java?

Problem

You have big Collection of objects and would like to partition by NUMBER elements. As a result you'd like to have Collection with Collection, each of them containing NUMBER elements.

For example:

You have list with 10 elements and want to split it by 3 elements:

Input:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Output:

[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

Solution 1 (vanilla)

    static <T> List<List<T>> partition(List<T> list, final int size) {
        if (list == null) {
            throw new NullPointerException("The list parameter is null.");
        }

        if (size <= 0) {
            throw new IllegalArgumentException(
                    "The size parameter must be more than 0.");
        }

        List<List<T>> parts = new ArrayList<List<T>>();
        final int N = list.size();
        for (int i = 0; i < N; i += size) {
            parts.add(new ArrayList<T>(
                    list.subList(i, Math.min(N, i + size)))
            );
        }
        return parts;
    }

Solution 2 (guava)

Google Guava has an useful method in Lists

List<List<Object>> partitionedList = Lists.partition(originalList, 3);  

Read Also:

Guava documentation
JavaCollections documentation
[RUS] JavaCollections useful tips

Published:
comments powered by Disqus