VOOZH about

URL: https://www.geeksforgeeks.org/java/stream-reduce-java-examples/

⇱ Stream.reduce() in Java with examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Stream.reduce() in Java with examples

Last Updated : 28 Aug, 2024

In Java, the Stream.reduce() method is used to perform a reduction on the elements of a stream using an associative accumulation function and returns an Optional. It is commonly used to aggregate or combine elements into a single result, such as computing the maximum, minimum, sum, or product.

Syntax:

T reduce(T identity, BinaryOperator<T> accumulator);
  • identity: An initial value of type T.
  • accumulator: A function that combines two values of type T.

Examples of Stream.reduce() in Java

Example 1: Get the Longest String


Output
GeeksforGeeks

Explanation:

  • Purpose: Finds the longest string in the list.
  • Lambda Expression: Compares two strings and returns the longer one.
  • Result: An Optional because the list might be empty.

Example 2: Combine Strings


Output
Geeks-for-Geeks


Explanation:

  • Purpose: Concatenates all strings in the array, separated by hyphens.
  • Lambda Expression: Concatenates two strings with a hyphen.
  • Result: An Optional because the stream might be empty.

Example 3: Sum of All Elements


Output
The sum of all elements is 16


Explanation:

  • Purpose: Computes the sum of all integers in the list.
  • Lambda Expression: Adds each element to the accumulator.
  • Identity Value: 0, which serves as the starting value.

Example 4: Product of All Numbers in a Range


Output
The product is : 5040

Explanation:

  • Purpose: Calculates the product of integers in the range [2, 8).
  • Lambda Expression: Multiplies two numbers.
  • Default Value: -1, used if the stream is empty.

Key Points:

  • The reduce method can be used for various reduction operations.
  • The result of reduce is an Optional because the stream might be empty.
  • reduce requires an associative operation to combine elements.
  • When using reduce with a non-empty stream, specifying an identity value (like 0 for sum) simplifies the operation without needing to handle Optional.

These examples and explanations demonstrate how to effectively use Stream.reduce() for different operations in Java.

Comment