Java : Stream.Builder with Examples

Stream.Builder (Java SE 18 & JDK 18) API Examples.
You will find code examples on most Stream.Builder methods.


Summary

A mutable builder for a Stream. This allows the creation of a Stream by generating elements individually and adding them to the Builder (without the copying overhead that comes from using an ArrayList as a temporary buffer.)

Class diagram

final var builder = Stream.<String>builder();

final var stream = builder.add("aaa").add("bbb").add("ccc").build();

System.out.println("-- forEach --");
stream.forEach(System.out::println);

// Result
// ↓
//-- forEach --
//aaa
//bbb
//ccc

Methods

void accept (T t)

Adds an element to the stream being built.

final var builder = Stream.<String>builder();

builder.accept("aaa");
builder.accept("bbb");
builder.accept("ccc");

final var stream = builder.build();

System.out.println("-- forEach --");
stream.forEach(System.out::println);

// Result
// ↓
//-- forEach --
//aaa
//bbb
//ccc

default Stream.Builder<T> add (T t)

Adds an element to the stream being built.

final var builder = Stream.<String>builder();

final var stream = builder.add("aaa").add("bbb").add("ccc").build();

System.out.println("-- forEach --");
stream.forEach(System.out::println);

// Result
// ↓
//-- forEach --
//aaa
//bbb
//ccc

Stream<T> build ()

Builds the stream, transitioning this builder to the built state.

Please see add(T t).

Methods declared in Consumer

andThen

Please see the link below.


Related posts

To top of page