Java 8 Streams - Program To Break A List Into Batches Of Given Size

In this post, we will show how to break a list into batches of a given size.


Example 1: Convert List of Characters into batches of a given size

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) {

List<Character> list = Arrays
.asList('a', 'b', 'c', 'd', 'e',
'f', 'g', 'h', 'i', 'j');

int chunkSize = 3;
AtomicInteger ai = new AtomicInteger();

Collection<List<Character>> chunkedOrders = list.stream()
.collect(Collectors.groupingBy(item -> ai
.getAndIncrement() / chunkSize))
.values();

chunkedOrders.forEach(chunk -> {
System.out.println("Processing" + " "
+ chunk.size() + " "
+ " data, sublist = " + chunk);

});

}
}


Output:

Processing 3  data, sublist = [a, b, c]
Processing 3  data, sublist = [d, e, e]
Processing 3  data, sublist = [f, g, h]
Processing 2  data, sublist = [i, j]


  1. The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored.
  2. The asList() method of java.util.Arrays class is used to return a fixed-size list backed by the specified array. This method acts as a bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
  3. An AtomicInteger is used in applications such as atomically incremented counters, and cannot be used as a replacement for an Integer. However, this class does extend Number to allow uniform access by tools and utilities that deal with numerically-based classes.
  4. stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
  5. Java Stream collect() performs a mutable reduction operation on the elements of the stream. This is a terminal operation.
  6. The groupingBy() method of Collectors class in Java are used for grouping objects by some property and storing results in a Map instance. In order to use it, we always need to specify a property by which the grouping would be performed.
  7. getAndIncrement() is an inbuilt method in java that increases the given value by one and returns the value before updating which is of data-type int.



Example 2: Convert List of Users into batches of a given size

User.java

public class User {
private String name;
private String email;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return "User [email=" + email + ", name=" + name + "]";
}
public User(String name, String email) {
this.name = name;
this.email = email;
}
}


Main.java

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class Main {

public static void main(String[] args) throws Exception {

List<User> list = Arrays
.asList(
new User("pekka", "pekka@email.cim"),
new User("xray", "xray@email.cim"),
new User("tesla", "tesla@email.cim"),
new User("gama", "gama@email.cim"),
new User("beta", "beta@email.cim"),
new User("alpha", "alpha@email.cim"),
new User("giga", "giga@email.cim"));

int chunkSize = 3;
AtomicInteger ai = new AtomicInteger();

Collection<List<User>> chunkedOrders = list.stream()
.collect(Collectors.groupingBy(item -> ai
.getAndIncrement() / chunkSize))
.values();

chunkedOrders.forEach(chunk -> {
System.out.println("Processing" + " "
+ chunk.size() + " "
+ " data, sublist = " + chunk);

});

}
}


Output:

Processing 3  data, sublist = [User [email=pekka@email.cim, name=pekka], User [email=xray@email.cim, name=xray], User [email=tesla@email.cim, name=tesla]]
Processing 3  data, sublist = [User [email=gama@email.cim, name=gama], User [email=beta@email.cim, name=beta], User [email=alpha@email.cim, name=alpha]]
Processing 1  data, sublist = [User [email=giga@email.cim, name=giga]]

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete