Stream.builder() Method in Java
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
// 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().
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.
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.
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));
}
}
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-.
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);
}
}
[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.
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());
}
}
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().
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");
}
}
}
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
Consumerto 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
| Approach | When elements are known | Reusable? | Best for |
|---|---|---|---|
Stream.builder() | One by one, at run time | No, build once | A stream is the final goal |
new ArrayList<>() then stream() | One by one, at run time | Yes, stream many times | You also need the data later |
Stream.of(a, b, c) | All at once, in code | No | Fixed values |
Stream.concat(a, b) | As two existing streams | No | Joining two streams |
7. Common Mistakes and Best Practices
Forgetting the type witness
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:
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);
}
}
Internal: 2 To: ops@example.com;dev@example.com
Other mistakes to avoid
- Keeping a reference and adding later. Any
add()afterbuild()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 aConsumer.build()can be called once; later additions throwIllegalStateException.- Use a list instead when the elements must be read more than once.
9. References
Frequently Asked Questions (FAQ)
Q1. What is Stream.builder() used for?
It creates a Stream.Builder that lets you add elements one at a time, for example conditionally or in a loop, and then call build() to get an ordered stream of those elements without creating an intermediate collection.
Q2. What is the difference between add() and accept() in Stream.Builder?
Both add an element. accept() comes from the Consumer interface and returns void. add() is a default method that calls accept() and returns the builder, so you can chain calls.
Q3. Can I add elements after calling build()?
No. After build() the builder is in the built state, and add(), accept() or a second build() throw IllegalStateException.
Q4. Is there a builder for primitive streams?
Yes. IntStream.builder(), LongStream.builder() and DoubleStream.builder() return builders for primitive values, which avoid boxing.
Q5. Should I use Stream.builder() or an ArrayList?
Use a builder when a single stream is the end goal. Use an ArrayList when you need to read the elements more than once, check the size or access elements by index.