# reduce() method

In 
Published 2023-06-10

This tutorial explains how we can use reduce() method with Streams in Java.

Please take a look at the following example and read carefully the comments. The code is self-explanatory.

From the base application downloaded from Spring Initializr, I updated the main class as below:

DemoApplication.java
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);
	}
}

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