Stream.Builder build() in Java

Stream.Builder build() builds the stream, transitioning this builder to the built state.

Syntax :

Stream<T> build()

Exceptions :



  • IllegalStateException : If the builder has already transitioned to the built state, IllegalStateException is thrown. It signals that a method has been invoked at an illegal or inappropriate time. In other words, the Java environment or Java application is not in an appropriate state for the requested operation.

Return Value : The built stream.

Note : A stream builder has a lifecycle, which starts in a building phase, during which elements can be added, and then transitions to a built phase, after which elements may not be added. The built phase begins when the build() method is called, which creates an ordered stream whose elements are the elements that were added to the stream builder, in the order they were added.

Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to show the implementation
// of Stream.Builder build()
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        Stream.Builder<String> str_b = Stream.builder();
  
        str_b.add("Geeks");
        str_b.add("for");
        str_b.add("GeeksforGeeks");
        str_b.add("Data Structures");
        str_b.add("Geeks Classes");
  
        // creating the string stream
        Stream<String> s = str_b.build();
  
        // printing the elements
        s.forEach(System.out::println);
    }
}

chevron_right


Output :

Geeks
for
GeeksforGeeks
Data Structures
Geeks Classes

Example 1 :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code to show the implementation
// of Stream.Builder build()
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        Stream.Builder<String> str_b = Stream.builder();
  
        str_b.add("Geeks");
        str_b.add("for");
        str_b.add("GeeksforGeeks");
        str_b.add("Data Structures");
        str_b.add("Geeks Classes");
  
        // creating the string stream
        Stream<String> s = str_b.build();
  
        // printing the elements
        s.forEach(System.out::println);
    }
}

chevron_right


Output :

Geeks
for
GeeksforGeeks
Data Structures
Geeks Classes


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.