Partitioning a list in Java is a common task, especially when dealing with large datasets, batching, or displaying data in pages. The idea is simple: split a big list into smaller chunks of a specified size.
Let us look at a few clean and effective ways to partition a list in Java using:
- Core Java (Java 8 and above)
- Google Guava
- Apache Commons Collections
Each method has its pros and cons and is suitable for different use cases. Let’s dive in.
💡 1. Partitioning a List Using Core Java
If you’re sticking to the standard Java library, you’ll need to write a bit of logic yourself, but it’s straightforward and avoids external dependencies.
Here’s a quick utility method that does the job:
import java.util.ArrayList;
import java.util.List;
public class PureJavaPartition {
public static <T> List<List<T>> partition(List<T> list, int size) {
List<List<T>> partitions = new ArrayList<>();
for (int i = 0; i < list.size(); i += size) {
partitions.add(list.subList(i, Math.min(i + size, list.size())));
}
return partitions;
}
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> result = partition(numbers, 3);
result.forEach(System.out::println);
}
}
Code language: PHP (php)
Output
[1, 2, 3]
[4, 5, 6]
[7]
Code language: JSON / JSON with Comments (json)
We can also use the various methods available from Java 8. Java 8 introduced the powerful Stream API, which is great for manipulating collections in a functional way.
(a) Collectors.groupingBy()
We can also use Collectors.groupingBy() to group elements into buckets based on their index.
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class GroupingByPartition {
public static <T> List<List<T>> partition(List<T> list, int size) {
return IntStream.range(0, list.size())
.boxed()
.collect(Collectors.groupingBy(i -> i / size))
.values()
.stream()
.map(indices -> indices.stream().map(list::get).collect(Collectors.toList()))
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<Integer> numbers = IntStream.rangeClosed(1, 10).boxed().collect(Collectors.toList());
List<List<Integer>> result = partition(numbers, 4);
result.forEach(System.out::println);
}
}
Code language: PHP (php)
This approach is more verbose but uses Java functional programming style. It’s more useful for cases where you want to apply transformations or grouping logic during partitioning.
(b) Using Instream and Collectors
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class PartitionExample {
public static <T> List<List<T>> partition(List<T> list, int size) {
if (size <= 0) throw new IllegalArgumentException("Size must be greater than 0");
int numberOfChunks = (int) Math.ceil((double) list.size() / size);
return IntStream.range(0, numberOfChunks)
.mapToObj(i -> list.subList(i * size, Math.min((i + 1) * size, list.size())))
.collect(Collectors.toList());
}
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date", "fig", "grape", "kiwi");
List<List<String>> result = partition(words, 3);
result.forEach(System.out::println);
}
}
Code language: PHP (php)
✅ 2. Using Google Guava –
Lists.partition()
Google Guava offers a ready-to-use method: Lists.partition().
Maven dependency:
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>32.1.2-jre</version>
</dependency>
Code language: HTML, XML (xml)
Example:
import com.google.common.collect.Lists;
import java.util.List;
public class PartitionGuava {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> result = Lists.partition(numbers, 3);
result.forEach(System.out::println);
}
}
Code language: PHP (php)
Output:
[1, 2, 3]
[4, 5, 6]
[7]
Code language: JSON / JSON with Comments (json)
Guava’s approach is simple and readable, compared to doing it in core Java. It also makes your code cleaner with just one method call. Core java should provide a simple, cleaner method to parition a list in its future versions.
🔧 3. Apache Commons Collections – ListUtils.partition()
Another option is from the Apache Commons Collections. Similar to Guava, it offers a one-liner solution via ListUtils.partition().
Maven dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
Code language: HTML, XML (xml)
Example:
import org.apache.commons.collections4.ListUtils;
import java.util.List;
public class ApcheCommonsPartition {
public static void main(String[] args) {
List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6, 7);
List<List<Integer>> result = ListUtils.partition(numbers, 3);
result.forEach(System.out::println);
}
}
Code language: PHP (php)
If you are already using Apache Commons libraries in your project, then this is handy.
⚖️ Which One Should You Use?
Approach | Advantages | Disadvantages |
---|---|---|
Core Java | No dependencies, pure Java approach | Manual implementation, Verbose code, More code to write. |
Google Guava | Clean and intuitive API | Library dependency |
Apache Commons Collections | Simple and clean, widely used | Library dependency |
Final Thoughts
Partitioning a list is a small but powerful utility to have in your toolkit. Whether you’re handling pagination, breaking up a large job, or preparing data for parallel processing, it’s always good to know a few ways to handle it cleanly.
Leave a Reply