Sobes.tech
Middle+

What is the recursion method in Stream?

sobes.tech AI

Answer from AI

// Recursion is not directly supported in Stream API.  
// The method is called reduce.  

The reduce method in Stream API performs a fold operation on the stream elements into a single result value by applying a binary operation.

There are three overloads of the reduce method:

  1. Optional<T> reduce(BinaryOperator<T> accumulator): Applies the fold operator to the stream elements, returning an Optional<T>. Used when there is no initial value.

  2. T reduce(T identity, BinaryOperator<T> accumulator): Applies the fold operator starting with the specified initial value (identity). Returns the resulting value of type T.

  3. <U> U reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner): The most general form, suitable for parallel streams.

    • identity: The initial value of the accumulator.
    • accumulator: Combines a stream element with the accumulator.
    • combiner: Combines the results of parallel computations.

Example usage:

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

public class StreamReduceExample {  

    public static void main(String[] args) {  
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);  

        // Example 1: Sum of elements without initial value  
        Optional<Integer> sumOptional = numbers.stream()  
                                              .reduce((a, b) -> a + b);  
        sumOptional.ifPresent(sum -> System.out.println("Sum (Optional): " + sum));  

        // Example 2: Sum of elements with initial value  
        int sumWithIdentity = numbers.stream()  
                                     .reduce(0, (a, b) -> a + b);  
        System.out.println("Sum (with identity): " + sumWithIdentity);  

        // Example 3: Concatenation of strings with parallel stream  
        List<String> words = Arrays.asList("Hello", " ", "World", "!");  
        String combinedString = words.parallelStream()  
                                     .reduce("", // identity  
                                             (a, b) -> a + b, // accumulator  
                                             (a, b) -> a + b); // combiner  
        System.out.println("Concatenated string: " + combinedString);  
    }  
}  
What is the recursion method in Stream? — Java - sobes.tech