Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

18. How does the reduce() method work in Java 8 Streams?

The reduce() method is a terminal operation in Java 8 that combines all elements of a stream into a single result using a binary operation. It’s commonly used for summing numbers, concatenating strings, or computing aggregates.

πŸ—ΊοΈ Step-by-Step Instructions:

  1. Define a binary operation using a lambda or method reference.
  2. Apply reduce() with or without an identity value.
  3. With an identity: returns a concrete value. Without identity: returns an Optional.

πŸ“₯ Example Input:

List numbers = Arrays.asList(1, 2, 3, 4, 5);

πŸ† Using reduce() to sum values:

int sum = numbers.stream()
                 .reduce(0, (a, b) -> a + b);

βœ… Java 8 Solution:

import java.util.*;
import java.util.stream.*;

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

    int sum = numbers.stream()
                     .reduce(0, Integer::sum);

    System.out.println("Sum: " + sum);
  }
}

πŸ“˜ Detailed Explanation:

  • reduce(identity, accumulator): Applies a binary operation starting with a base value.
  • reduce(accumulator): Returns an Optional in case the stream is empty.
  • Works best when converting streams into a single result like sum, product, max, or string join.

πŸ› οΈ Use Cases:

  • Calculating total, product, or max values from a list.
  • Concatenating string values from a stream of words.
  • Implementing custom aggregation logic over data.