Builder Pattern for Stream Creation
You'll learn how to build streams incrementally when you don't know all the elements up front.
What Is Stream.Builder?
Sometimes you need to construct a stream element by element, based on runtime conditions or dynamic logic. Unlike Stream.of() where you provide all elements at once, Stream.Builder lets you add elements one at a time, then finalize the stream when you're ready.
Think of it like packing a suitcase for a trip: you don't throw everything in at once. You add items as you decide what you need, then zip it up when you're done.
How to Use Stream.Builder
The pattern has three steps:
- Create a builder using
Stream.builder() - Add elements incrementally with
.add() - Build the final stream with
.build()
Stream.Builder<String> builder = Stream.builder();
// Add elements conditionally
builder.add("First");
if (someCondition) {
builder.add("Second");
}
builder.add("Third");
// Finalize and use the stream
Stream<String> stream = builder.build();
stream.forEach(System.out::println);
When to Use It
This is particularly useful when:
- You're collecting elements from a loop or conditional logic
- The number of elements isn't known until runtime
- You're processing data that arrives incrementally
Stream.Builder<Integer> numbers = Stream.builder();
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
numbers.add(i);
}
}
Stream<Integer> evenNumbers = numbers.build();
Key Takeaway: Stream.Builder provides a flexible way to construct streams incrementally when elements aren't available all at once—just add elements as needed, then call .build() to finalize the stream.