Java 8 Stream reduce() operation with examples

Stream reduce()

Stream reduce() operation can be used when we want to derive a single value from a collection of values.

sum(), min(), max(), count() etc are examples of reduce operations.

reduce() applies a binary operator to each element in the stream where the first argument to the operator is the return value of the previous application and the second argument is the current stream element.

java 8 stream reduce
 

Using reduce() : Finding longest String from a List of String

Syntax of reduce():


Optional<T> reduce(BinaryOperator<T> accumulator)

Here, accumulator is a function that takes two parameters: a partial result of the reduction (in this example, the longest string so far) and the next element of the stream (in this example, next string).

 

package com.topjavatutorial.java8examples;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

public class StreamOperations {

  public static void main(String[] args) {
    List<String> countries = Arrays.asList("Germany", "England", "China",
        "Denmark", "Brazil", "France", "Australia");

    Optional<String> longestCountryName = countries.stream().reduce(
        (c1, c2) -> c1.length() > c2.length() ? c1 : c2);

    longestCountryName.ifPresent(System.out::println);

  }

}

The lambda expression passed to reduce() method takes two Strings and returns the the longer String.

The reduce() method iterated through the whole list, returns the longest String.

Output:

Australia

 

Using reduce() with identity

The result of the reduce() method is an Optional because the list on which reduce() is called may be empty.

If we want to set a default or a base value, we can pass that value as an extra parameter to an overloaded variation of the reduce() method.

Syntax of reduce():


T reduce(T identity, BinaryOperator<T> accumulator)

The identity element is both the initial value of the reduction and the default result if there are no elements in the stream. In this example, the identity element is an empty string.

String longestCountryName = countries.stream().reduce("",
    (c1, c2) -> c1.length() > c2.length() ? c1 : c2);

System.out.println("Longest Country Name is " + longestCountryName);

 
Here is another example of reduce() operation that calculates sum of numbers:

Example : Calculating sum of numbers using reduce() method

final List<Integer> numbers = Arrays.asList(1,2,3,4,5);

int sum = numbers.stream().reduce(0,(num1,num2) -> num1+num2);

System.out.println("Sum is " + sum);

Output:

Sum is 15

 

You may also like

Stream map() operation

Java 8 new features

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

Leave a Reply.. code can be added in <code> </code> tags