Contents

Split a list in java

Written by: David Vlijmincx

Introduction

In this blog post, we will explore a simple and efficient way to split a List into smaller chunks using Java without needing any third-party libraries. This approach can be handy for dealing with large data sets and optimizing performance. Whether it's for efficient processing or easier data manipulation, splitting a list can be a valuable tool.

How to chunk a list in Java

In the following example, a list of fruits is split into two groups using Java Streams and Collectors.groupingBy.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("pear");
fruits.add("Banana");
fruits.add("Orange");

AtomicInteger counter = new AtomicInteger();
int groupSize = 2;
Map<Integer, List<String>> listOfChunks = fruits.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / groupSize));

Return a List of lists containing chunks

The following example is almost the same as the previous one except for line 13. On line 13, we use the ArrayList constructor to create a list that contains the lists of chunks.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("pear");
fruits.add("Banana");
fruits.add("Orange");

AtomicInteger counter = new AtomicInteger();
int groupSize = 2;
Map<Integer, List<String>> mapOfChunks = fruits.stream()
.collect(Collectors.groupingBy(it -> counter.getAndIncrement() / groupSize));
// Create a list containing the lists of chunks
List<List<String>> ListOfChunks = new ArrayList<>(mapOfChunks.values());

Conclusion

While several third-party libraries and frameworks are available to accomplish this, it's possible to do it without relying on external dependencies. In this blog post, we have explored a simple approach to splitting a list using Java, which is easily adapted to different use cases.