Stream.reduce() in Java with examples

Many times, we need to perform operations where a stream reduces to single resultant value, for example, maximum, minimum, sum, product, etc. Reducing is the repeated process of combining all elements.

reduce operation 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 second argument is the current stream element.

Syntax :

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

Where, identity is initial value 
of type T and accumulator is a 
function for combining two values.

sum(), min(), max(), count() etc. are some examples of reduce operations. reduce() explicitly asks you to specify how to reduce the data that made it through the stream.

Let us see some examples to understand the reduce() function in a better way :
Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Implementation of reduce method
// to get the longest String
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // creating a list of Strings
        List<String> words = Arrays.asList("GFG", "Geeks", "for",
                                           "GeeksQuiz", "GeeksforGeeks");
  
        // The lambda expression passed to
        // reduce() method takes two Strings
        // and returns the the longer String.
        // The result of the reduce() method is
        // an Optional because the list on which
        // reduce() is called may be empty.
        Optional<String> longestString = words.stream()
                                   .reduce((word1, word2)
                             -> word1.length() > word2.length()
                                           ? word1 : word2);
  
        // Displaying the longest String
        longestString.ifPresent(System.out::println);
    }
}

chevron_right


Output :

GeeksforGeeks

Example 2 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Implementation of reduce method
// to get the combined String
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // String array
        String[] array = { "Geeks", "for", "Geeks" };
  
        // The result of the reduce() method is
        // an Optional because the list on which
        // reduce() is called may be empty.
        Optional<String> String_combine = Arrays.stream(array)
                                           .reduce((str1, str2)
                                           -> str1 + "-" + str2);
  
        // Displaying the combined String
        if (String_combine.isPresent()) {
            System.out.println(String_combine.get());
        }
    }
}

chevron_right


Output :

Geeks-for-Geeks

Example 3 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Implementation of reduce method
// to get the sum of all elements
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating list of integers
        List<Integer> array = Arrays.asList(-2, 0, 4, 6, 8);
  
        // Finding sum of all elements
        int sum = array.stream().reduce(0,
                (element1, element2) -> element1 + element2);
  
        // Displaying sum of all elements
        System.out.println("The sum of all elements is " + sum);
    }
}

chevron_right


Output :

The sum of all elements is 16

Example 4 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Implementation of reduce method
// to get the product of all numbers
// in given range.
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // To get the product of all elements
        // in given range excluding the
        // rightmost element
        int product = IntStream.range(2, 8)
                     .reduce((num1, num2) -> num1 * num2)
                     .orElse(-1);
  
        // Displaying the product
        System.out.println("The product is : " + product);
    }
}

chevron_right


Output :

The product is : 5040


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.