#
reduce() method
This tutorial explains how we can use reduce() method with Streams in Java.
reduce()
method produce one single result (this is a terminal operation) from a sequence of elements,
by repeatedly applying a combining operation to the elements in the stream.
Please take a look at the following example and read carefully the comments. The code is self-explanatory.
This example is created from a simple Spring Boot application created with Spring Initializr. I am using Maven, Java 17, Spring Boot 3.1.0.
From the base application downloaded from Spring Initializr, I updated the main class as below:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.*;
import java.util.concurrent.ExecutionException;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
Integer[] numbers = {10, 20, 30};
Integer sum = Arrays.stream(numbers)
// Calculate the SUM of the number in the stream
.reduce(0, (a,b) -> a+b);
System.out.println("SUM="+sum);
}
}
When we consider reduce(0, (a,b) -> a+b)
, "0" is the initial value, "a" is the partial result (accumulator)
and "b" is the current element.
The same result could be done by using the method reference (Integer::sum
):
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.*;
import java.util.concurrent.ExecutionException;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ApplicationContext appContext = SpringApplication.run(DemoApplication.class, args);
Integer[] numbers = {10, 20, 30};
Integer sum = Arrays.stream(numbers)
// Calculate the SUM of the number in the stream
.reduce(Integer::sum)
.get();
System.out.println("SUM="+sum);
}
}
When I run this code I receive:
SUM=60
Process finished with exit code 0
When we are working with Streams, we can have:
- INTERMEDIATE operations:
filter
,map
,limit
,sorted
,peak
,distinct
,skip
,flatMap
- TERMINAL operations:
forEach
,count
,sum
,min
,collect
,reduce
,anyMatch
,noneMatch
,allMatch