IntStream.Builder build() in Java with Examples
IntStream.Builder
is a helper interface in Java that is used to build a stream of primitive integers. It is a mutable container that can be used to add elements to the stream. The build()
method is used to create an IntStream
from the elements added to the builder.
Syntax:
IntStream.Builder builder = IntStream.builder();
builder.add(int value);
IntStream stream = builder.build();
Example 1: Creating an IntStream using IntStream.Builder
IntStream.Builder builder = IntStream.builder();
builder.add(1);
builder.add(2);
builder.add(3);
IntStream stream = builder.build();
stream.forEach(System.out::println);
Output:
1
2
3
Example 2: Creating an IntStream using IntStream.Builder with a loop
IntStream.Builder builder = IntStream.builder();
for (int i = 1; i <= 5; i++) {
builder.add(i);
}
IntStream stream = builder.build();
stream.forEach(System.out::println);
Output:
1
2
3
4
5
Example 3: Creating an IntStream using IntStream.Builder with an array
int[] arr = {1, 2, 3, 4, 5};
IntStream.Builder builder = IntStream.builder();
for (int i : arr) {
builder.add(i);
}
IntStream stream = builder.build();
stream.forEach(System.out::println);
Output:
1
2
3
4
5