Stream.Builder build() in Java


The build() method of the Stream.Builder class builds the stream, transitioning this builder to the built state. The syntax is as follows −

Stream<T> build()

Following is an example to implement the build() method of the Stream.Builder class −

Example

import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream.Builder<String> builder = Stream.builder();
      builder.add("Production");
      builder.add("Marketing");
      builder.add("Finance");
      builder.add("Sales");
      builder.add("Operations");
      Stream<String> stream = builder.build();
      stream.forEach(System.out::println);
   }
}

Output

Production
Marketing
Finance
Sales
Operations

Example

Let us see another example of build() method wherein we are adding elements to the stream using the accept() method −

import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream.Builder<String> builder = Stream.builder();
      builder.accept("k");
      builder.accept("l");
      builder.accept("m");
      builder.accept("n");
      builder.accept("o");
      builder.accept("p");
      builder.accept("q");
      builder.accept("r");
      builder.accept("s");
      builder.accept("t");
      Stream<String> stream = builder.build();
      stream.forEach(System.out::println);
   }
}

Output

K
l
m
n
o
p
q
r
s
t

Updated on: 24-Sep-2019

725 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements