Java Stream Reduce with Examples

In this article, we will learn Java Stream Reduce with examples. Streams reduction operation helps us to get results from streams elements by accumulation in sequence. I will show some examples of Stream.reduce() method to make the concepts more clear. Let’s start!

Java Stream Reduce

With Stream.reduce(), we can do accumulative operations like the sum of all numbers or factorials. Stream.reduce() method helps us to combine elements into one single object. It is working like an accumulator and in the example below, we will calculate the sum of numbers.

Stream Reduce Sum Example

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class StreamReduce {
    List<Integer> numbers = new ArrayList<>();

    @BeforeEach
    void setup() {
        Collections.addAll(numbers, 1, 2, 3, 4);
    }

    /**
     * Reduce helps us to combine elements into one single object.
     * It is working like an accumulator. Below we calculate sum of numbers.
     */
    @Test
    @Order(1)
    public void streamReduceSumTest() {
        Instant start = Instant.now();
        Optional<Integer> sum = numbers.stream()
            .reduce((a, b) -> a + b);

        sum.ifPresent(result -> System.out.println("Sum is: " + result));
        Instant end = Instant.now();
        System.out.println("Elapsed time of streamReduceSumTest: " + Duration.between(start, end).toNanos());
    }
}

Output

Java Stream Reduce Sum Example

We can also use parallelStream() to run the Java Reduce operation in parallel. If you have IO operations, longer operations parallel execution performs better. If you have a simple example like this, parallel execution is not the wiser approach and performs slower.

@Test
@Order(1)
public void streamReduceParallelSumTest() {
    Instant start = Instant.now();
    Optional<Integer> sum = numbers.parallelStream()
        .reduce((a, b) -> a + b);

    sum.ifPresent(result -> System.out.println("Sum is: " + result));
    Instant end = Instant.now();
    System.out.println("Elapsed time of streamReduceParallelSumTest: " + Duration.between(start, end).toNanos());
}

Output

java stream reduce parallel execution

Let’s do a sum operation without reduce and check the performance. This time, we will use a primitive type stream.

@Test
@Order(3)
public void intStreamSumTest() {
    Instant start = Instant.now();
    int sum = numbers.stream()
        .mapToInt(number -> number)
        .sum();
    
    System.out.println("Sum of intStream operation: " + sum);
    Instant end = Instant.now();
    System.out.println("Elapsed time of intStreamSumTest: " + Duration.between(start, end).toNanos());
}

Output

As you seen below the performance of this implementation is worse than stream.reduce() version.

Java Stream Sum Example

Stream Reduce Factorial Example

In the example below, we will do a factorial example with Java Stream Reduce. 

@Test
@Order(2)
public void streamReduceFactorialTest() {
    Instant start = Instant.now();
    Optional<Integer> sum = numbers.stream()
        .reduce((a, b) -> a * b);

    sum.ifPresent(result -> System.out.println("Factorial is: " + result));
    Instant end = Instant.now();
    System.out.println("Elapsed time of streamReduceFactorialTest: " + Duration.between(start, end).toNanos());
}

Output

Java Stream Reduce Factorial Example

Github Project

StreamReduce.java

In this article, I explained what is Stream.reduce() with sum and factorial examples. See you in the next articles.

Thanks for reading,
Onur Baskirt

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.