Stream.Builder add() method in Java
Stream.Builder add(T t) is used to insert an element into the element in the building phase of stream. It adds an element to the stream being built.
Syntax:
default Stream.Builder<T> add(T t)
Parameters: This method adds a mandatory parameter t which is the element to input into the stream.
Exceptions: This method throws IllegalStateException: when the builder has already transitioned to the built state. It means that the stream has entered the built phase and now no it can’t be changed. Hence no more elements can be added into the stream.
Below are the examples to illustrate add() method:
Example 1:
import java.util.stream.Stream;
class GFG {
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" );
Stream<String> s = str_b.build();
System.out.println( "Stream successfully built" );
s.forEach(System.out::println);
}
}
|
Output:
Stream successfully built
Geeks
for
GeeksforGeeks
Data Structures
Geeks Classes
Example 2: To illustrate IllegalStateException
import java.util.stream.Stream;
class GFG {
public static void main(String[] args)
{
Stream.Builder<String> str_b = Stream.builder();
str_b.add( "5" );
str_b.add( "6" );
str_b.add( "7" );
str_b.add( "8" );
str_b.add( "9" );
Stream<String> s = str_b.build();
System.out.println( "Stream successfully built" );
s.forEach(System.out::println);
try {
str_b.add( "50" );
}
catch (Exception e) {
System.out.println( "Exception thrown "
+ "when now adding element into the stream: "
+ e);
}
}
}
|
Output:
Stream successfully built
5
6
7
8
9
Exception thrown when now adding element into the stream: java.lang.IllegalStateException
Last Updated :
06 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...