The Wayback Machine - https://web.archive.org/web/20250112110520/https://www.geeksforgeeks.org/stream-reduce-java-examples/
Open In App

Stream.reduce() in Java with examples

Last Updated : 28 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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

Java
// 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 Optional because the list might be empty.

Example 2: Combine Strings

Java
// 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 Optional because the stream might be empty.

Example 3: Sum of All Elements

Java
// 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

Java
// 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 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.


Master JAVA and also get 90% fee refund on completing 90% course in 90 days! Take the Three 90 Challenge today.

After successfully processing refunds worth over INR 5 Cr, GeeksforGeeks is back with the Three 90 challenge and this is your chance to upskill and get 90% refund. What more motivation do you need? Start the challenge right away!


Next Article

Similar Reads

three90RightbarBannerImg