00:00

Stream.builder() Method in Java

Last updated:

Stream.builder() is a static method of java.util.stream.Stream, added in Java 8, that returns a Stream.Builder<T>. You add elements to the builder one at a time with add() or accept(), and then call build() to get an ordered stream of those elements.

It is a stream creation operation for cases where the elements are decided step by step, for example inside if statements or a loop, and you do not want an intermediate list. This tutorial covers the builder's methods, its build-once rule, and when a list is the better choice.

1. Syntax and Method Signatures

Stream.Builder.java (API)
// java.util.stream.Stream (Java 8)
static <T> Stream.Builder<T> builder()

// java.util.stream.Stream.Builder<T> extends Consumer<T> (Java 8)
void accept(T t)                       // adds an element
default Stream.Builder<T> add(T t)     // adds an element and returns the builder (chainable)
Stream<T> build()                      // finishes building and returns the stream

Because Builder extends Consumer<T>, you can pass a builder wherever a Consumer is expected, for example list.forEach(builder). Primitive versions exist too: IntStream.builder(), LongStream.builder() and DoubleStream.builder().

Usage
Stream<String> parts = Stream.<String>builder()
        .add("header")
        .add("body")
        .add("footer")
        .build();

2. How Stream.builder() Works

A builder has two phases. In the building phase, each add() or accept() appends an element. Calling build() moves it to the built phase and returns a stream that delivers the elements in the order they were added. From then on, add(), accept() and a second build() throw IllegalStateException.

The JDK implementation is optimised for small streams: a builder with zero or one element avoids allocating a buffer, and larger ones use an internal buffer that grows in chunks. The resulting stream is sequential, ordered and sized.

Lifecycle of a Stream.Builder A builder is created with Stream.builder. Elements are added with add or accept while the builder is in the building phase. build is called once and switches the builder to the built phase, returning an ordered stream. Adding after build throws IllegalStateException. builder()empty builder CREATE add("a")building add("b")building build()once only Stream<T>a, b in order RESULT ADD ELEMENTS, THEN BUILD add() after build() throws IllegalStateException
Figure 1: Elements are added in order during the building phase. build() may be called once; after that the builder rejects new elements.

3. Java Examples

Example 1: Adding elements conditionally

Build the list of sections for a customer email, where some sections appear only for certain customers.

EmailSections.java
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class EmailSections {

    static String sections(boolean premium, boolean hasDiscount) {
        Stream.Builder<String> builder = Stream.builder();
        builder.add("greeting");
        if (premium) {
            builder.add("premium-perks");
        }
        if (hasDiscount) {
            builder.add("discount-code");
        }
        builder.add("footer");
        return builder.build().collect(Collectors.joining(" | "));
    }

    public static void main(String[] args) {
        System.out.println("Basic:   " + sections(false, false));
        System.out.println("Premium: " + sections(true, true));
    }
}
Output
Basic:   greeting | footer
Premium: greeting | premium-perks | discount-code | footer

How it works: The builder collects only the sections that apply, in the order they were added, and build() turns them into a stream that is joined into one line.

Example 2: Chaining add() calls

Build a stream of HTTP headers in one expression and keep only the ones that start with X-.

HeaderBuilder.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class HeaderBuilder {

    public static void main(String[] args) {
        List<String> custom = Stream.<String>builder()
                .add("Content-Type")
                .add("X-Request-Id")
                .add("Authorization")
                .add("X-Trace")
                .build()
                .filter(header -> header.startsWith("X-"))
                .collect(Collectors.toList());

        System.out.println(custom);
    }
}
Output
[X-Request-Id, X-Trace]

How it works: add() returns the builder, so calls can be chained. The type witness Stream.<String>builder() tells the compiler the element type, because there is no variable for it to infer from.

Example 3: Using the builder as a Consumer

Read readings from a legacy callback-style API, which accepts a Consumer, into a stream.

BuilderAsConsumer.java
import java.util.function.Consumer;
import java.util.stream.DoubleStream;
import java.util.stream.Stream;

public class BuilderAsConsumer {

    // A legacy API that pushes values to a callback
    static void readSensor(Consumer<Double> callback) {
        double[] values = {21.5, 22.0, 22.8, 23.4};
        for (double value : values) {
            callback.accept(value);
        }
    }

    public static void main(String[] args) {
        Stream.Builder<Double> builder = Stream.builder();
        readSensor(builder);                       // the builder is a Consumer<Double>

        double average = builder.build()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(Double.NaN);

        System.out.printf("Average temperature: %.2f%n", average);

        DoubleStream.Builder primitive = DoubleStream.builder();
        primitive.add(1.5).add(2.5);
        System.out.println("Primitive builder sum: " + primitive.build().sum());
    }
}
Output
Average temperature: 22.43
Primitive builder sum: 4.0

How it works: Since Stream.Builder implements Consumer, it can be handed to any method that pushes values to a callback. DoubleStream.builder() does the same for primitive double values without boxing.

Example 4: The builder can be built only once

Show what happens when code tries to add to a builder after build().

BuildOnce.java
import java.util.stream.Stream;

public class BuildOnce {

    public static void main(String[] args) {
        Stream.Builder<String> builder = Stream.builder();
        builder.add("alpha").add("beta");

        Stream<String> stream = builder.build();
        System.out.println("Elements: " + stream.count());

        try {
            builder.add("gamma");
        } catch (IllegalStateException e) {
            System.out.println("add after build: IllegalStateException");
        }
        try {
            builder.build();
        } catch (IllegalStateException e) {
            System.out.println("second build:    IllegalStateException");
        }
    }
}
Output
Elements: 2
add after build: IllegalStateException
second build:    IllegalStateException

How it works: Once built, a builder is finished. If you need several streams from the same elements, collect them into a list first and call list.stream() each time.

4. Real-World Use Cases

  • Dynamic report columns: add columns based on user permissions or feature flags, then stream them into a header row.
  • Adapting callback APIs: pass a builder as the Consumer to a parser or SDK that pushes values.
  • Assembling validation messages: add a message for each failed rule, then build a stream to join or count them.

5. Important Points

  • Empty builder: build() with no elements returns an empty stream.
  • Nulls are accepted as elements; downstream lambdas must handle them.
  • Order is insertion order, and duplicates are kept.
  • Not thread-safe: adding from several threads at once needs external synchronisation.
  • Single use: the builder can be built once, and the resulting stream can be consumed once.

6. Stream.builder() vs Other Approaches

ApproachWhen elements are knownReusable?Best for
Stream.builder()One by one, at run timeNo, build onceA stream is the final goal
new ArrayList<>() then stream()One by one, at run timeYes, stream many timesYou also need the data later
Stream.of(a, b, c)All at once, in codeNoFixed values
Stream.concat(a, b)As two existing streamsNoJoining two streams

7. Common Mistakes and Best Practices

Forgetting the type witness

Surprising
var stream = Stream.builder().add("a").add("b").build();   // Stream<Object>, not Stream<String>

Without a target type, the compiler infers Object. Write Stream.<String>builder() or assign the builder to a typed variable first.

Using a builder where a list is clearer

If you will stream the elements more than once, or need size() or get(), build a list instead:

ListWhenReused.java
import java.util.ArrayList;
import java.util.List;

public class ListWhenReused {

    public static void main(String[] args) {
        List<String> recipients = new ArrayList<>();
        recipients.add("ops@example.com");
        recipients.add("dev@example.com");

        long internal = recipients.stream().filter(r -> r.endsWith("@example.com")).count();
        String joined = String.join(";", recipients);

        System.out.println("Internal: " + internal);
        System.out.println("To: " + joined);
    }
}
Output
Internal: 2
To: ops@example.com;dev@example.com

Other mistakes to avoid

  • Keeping a reference and adding later. Any add() after build() throws.
  • Sharing a builder across threads. Its internal buffer is not synchronised.
  • Using the boxed builder for numbers. IntStream.builder() avoids boxing.

8. Summary

  • Stream.builder() returns a builder to which you add elements one at a time.
  • add() is chainable; accept() makes the builder usable as a Consumer.
  • build() can be called once; later additions throw IllegalStateException.
  • Use a list instead when the elements must be read more than once.

9. References