Stream of() method in Java
A static method offered by the Stream interface in the Java Stream API is called Stream of() in Java. It enables us to turn a series of elements into a stream. It can receive a finite amount of arguments and build a stream out of them.
Syntax
Streamstream = Stream.of(element1, element2, ..., elementN);
Stream of(T t)
The method Stream of(T t) is used to create a sequential stream containing a single element.
Syntax
static Stream of(T t)
The single element in the Stream, t, is a required parameter for the above method. The function Stream of(T t) yields a sequential stream that includes the single input element.
Implementation
FileName:StreamMethodImplementation.java
import java.util.stream.Stream; public class StreamMethodImplementation { public static void main(String[] args) { // Creating a sequential stream containing a single element (in the above case, an Integer) Streamstream = Stream.of(10); stream.forEach(System.out::println); } }
Output:
10
Stream of(T… values)
The `Stream.of(T... values)` function generates a stream with the given values arranged in a sequential order.
Syntax
staticStream of(T... values)
The parameter values in the above instance represent the elements that will make up the new stream.
The values supplied as arguments are the elements of the sequentially ordered stream that the above approach returns. It is especially useful when generating a stream based on a predefined set of values.
Implementation
FileName:StreamMethodImplementation1.java
import java.util.stream.Stream; public class StreamMethodImplementation1 { public static void main(String[] args) { // Creating a sequential ordered stream with specified values Streamstream = Stream.of("apple", "banana", "orange"); stream.forEach(System.out::println); } }
Output:
apple banana orange