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
// Implementation of reduce method
// to get the longest String
import java.util.*;
class GFG {
public static void main(String[] args) {
// Creating a list of Strings
List<String> words = Arrays.asList("GFG", "Geeks", "for", "GeeksQuiz", "GeeksforGeeks");
// Using reduce to find the longest string in the list
Optional<String> longestString = words.stream()
.reduce((word1, word2) -> word1.length() > word2.length() ? word1 : word2);
// Displaying the longest String
longestString.ifPresent(System.out::println);
}
}
Output
GeeksforGeeks
Explanation:
- Purpose: Finds the longest string in the list.
- Lambda Expression: Compares two strings and returns the longer one.
- Result: An
Optionalbecause the list might be empty.
Example 2: Combine Strings
// Implementation of reduce method
// to get the combined String
import java.util.*;
class GFG {
public static void main(String[] args) {
// String array to combine
String[] array = { "Geeks", "for", "Geeks" };
// Using reduce to concatenate strings with a hyphen
Optional<String> combinedString = Arrays.stream(array)
.reduce((str1, str2) -> str1 + "-" + str2);
// Displaying the combined String
combinedString.ifPresent(System.out::println);
}
}
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
Optionalbecause the stream might be empty.
Example 3: Sum of All Elements
// Implementation of reduce method
// to get the sum of all elements
import java.util.*;
class GFG {
public static void main(String[] args) {
// Creating list of integers
List<Integer> numbers = Arrays.asList(-2, 0, 4, 6, 8);
// Using reduce to find the sum of all elements
int sum = numbers.stream()
.reduce(0, (element1, element2) -> element1 + element2);
// Displaying the sum of all elements
System.out.println("The sum of all elements is " + sum);
}
}
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
// Implementation of reduce method
// to get the product of all numbers
// in given range.
import java.util.*;
import java.util.stream.IntStream;
class GFG {
public static void main(String[] args) {
// Calculating the product of all numbers in the range [2, 8)
int product = IntStream.range(2, 8)
.reduce((num1, num2) -> num1 * num2)
.orElse(-1); // Provides -1 if the stream is empty
// Displaying the product
System.out.println("The product is : " + product);
}
}
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
reducemethod can be used for various reduction operations. - The result of
reduceis anOptionalbecause the stream might be empty. reducerequires an associative operation to combine elements.- When using
reducewith a non-empty stream, specifying an identity value (like0for sum) simplifies the operation without needing to handleOptional.
These examples and explanations demonstrate how to effectively use Stream.reduce() for different operations in Java.