Java Stream of() Method Tutorial

In this section, we will learn what the Stream of() method is and how to use it in Java.

What is Java Stream of() Method?

The Java Stream of() method is used to create a stream of the elements that we set as the arguments of this method.

Basically, this method takes one or more elements as its arguments and creates a sequential ordered stream of the specified elements.

Java of() Method Syntax:

static <T> Stream<T> of(T t)

@SafeVarargs

static <T> Stream<T> of(T... values)

of() Method Parameters:

The method has two variants:

For the first variant, it takes only one argument which will create a single element type of stream.

For the second variant, it takes over one element and they come the elements of the returned stream of this method.

Note: we could also pass a reference of an array to this method and it will extract its elements and creates a stream as a result.

of() Method Return Value:

The return value of this method is a fresh stream that contains the elements that we’ve specified as the arguments of the methods.

of() Method Exceptions:

The method does not throw an exception.

Example: using Stream of() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,7,86,54,5);
        stream.forEach(e->System.out.print(e+", "));
    }
}

Output:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3, 23, 4, 23, 423, 2, 34, 56, 7, 86, 54, 5,

Leave a Reply