Course contentsShow
← Java
Lesson 1510 of 2,87033. Streams API: Terminal OperationsFree lesson

The Three-Argument reduce: Handling Different Types

Understanding <U> U reduce(U identity, BiFunction<U,T,U>, BinaryOperator<U>) for reducing to a different type.

The Three-Argument reduce: Handling Different Types

What You'll Learn

You'll learn how to use the three-argument form of reduce to transform a stream into a completely different type than the stream elements themselves.

The Core Idea

So far, you've used reduce to collapse stream elements into a single value of the same type as the stream. But what if you want to reduce a stream of Integer into a String, or a stream of String into a List? That's where the three-argument version shines.

The signature is:

<U> U reduce(U identity, BiFunction<U, T, U> accumulator, BinaryOperator<U> combiner)

Here's what each parameter does:

  • U identity: The starting value for your result (of the new type U)
  • BiFunction<U, T, U> accumulator: Takes the current result (type U) and the next stream element (type T), returns updated result (type U)
  • BinaryOperator<U> combiner: Combines two results (both type U) when processing in parallel

Think of It Like a Factory Assembly Line

Imagine you have boxes of parts (stream elements of type T) and you're building a car (result of type U). The accumulator attaches each part to the car-in-progress. The combiner merges partially-built cars from different assembly lines when working in parallel.

A Concrete Example

Stream<String> words = Stream.of("hello", "world", "java");

Integer totalLength = words.reduce(
    0,                                    // identity: starting with 0
    (length, word) -> length + word.length(),  // accumulator: add each word's length
    (len1, len2) -> len1 + len2          // combiner: merge partial sums
);
// totalLength = 14

Here we reduce a Stream<String> into an Integer by summing all word lengths.

Key Takeaway: The three-argument reduce lets you transform a stream into a different type by providing an identity value, an accumulator that incorporates each element into your result, and a combiner for parallel processing.