Java Reference
In-Depth Information
The
accept()
and
add()
methods add elements to the stream being built. You might wonder about the existence of
two methods in the builder to add elements. The
Stream.Builder<T>
interface inherits from the
Consumer<T>
interface,
and therefore it inherits the
accept()
method from the
Consumer<T>
interface. You can pass a builder's instance to a
method that accepts a consumer and the method can add elements to the builder using the accept method.
The
add()
method returns the reference to the builder that makes it suitable for adding multiple elements using
method chaining. Once you are done adding elements, call the
build()
method to create the stream. You cannot
add elements to the stream after you call the build() method; doing so results in an
IllegalStateException
runtime
exception. The following snippet of code uses the builder pattern to create a stream of four strings:
Stream<String> stream = Stream.<String>builder()
.add("Ken")
.add("Jeff")
.add("Chris")
.add("Ellen")
.build();
Note that the code specifies the type parameter as
String
when it obtains the builder
Stream.
<String>
builder()
.
The compiler fails to infer the type parameter if you do not specify it. If you obtain the builder separately, the compiler
will infer the type as
String
, as shown:
// Obtain a builder
Stream.Builder<String> builder = Stream.builder();
// Add elements and build the stream
Stream<String> stream = builder.add("Ken")
.add("Jeff")
.add("Chris")
.add("Ellen")
.build();
The
IntStream
interfaces contain two static methods:
•
IntStream range(int start, int end)
IntStream rangeClosed(int start, int end)
.
They produce an
IntStream
that contains ordered integers between the specified
start
and
end
. The specified
end
is exclusive in the
range()
method whereas it is inclusive in the
rangeClosed()
method. The following snippet of
code uses both methods to create an
IntStream
having integers 1, 2, 3, 4, and 5 as their elements:
•
// Create an IntStream containing 1, 2, 3, 4, and 5
IntStream oneToFive = IntStream.range(1, 6);
// Create an IntStream containing 1, 2, 3, 4, and 5
IntStream oneToFive = IntStream.rangeClosed(1, 5);
Like the
IntStream
interface, the
LongStream
class also contains
range()
0and
rangeClosed()
methods that
takes arguments of type
long
and return a
LongStream
.