Stream.of(T t) in Java with examples

Stream of(T t) returns a sequential Stream containing a single element i.e, a singleton sequential stream. A sequential stream work just like for-loop using a single core. On the other hand, a Parallel stream divide the provided task into many and run them in different threads, utilizing multiple cores of the computer.

Syntax :

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

Where, Stream is an interface and T
is the type of stream elements.
t is the single element and the
function returns a singleton 
sequential stream.

Example 1 : Singleton string stream.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream.of()
// to get sequential Stream
// containing a single element.
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // creating a stream of Strings
        // and printing sequential Stream
        // containing a single element
        Stream<String> stream = Stream.of("Geeks");
  
        stream.forEach(System.out::println);
    }
}

chevron_right


Output :

Geeks

Example 2 : Singleton Integer Stream.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream.of()
// to get sequential Stream
// containing a single element.
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // creating a stream of Integer
        // and printing sequential Stream
        // containing a single element
        Stream<Integer> stream = Stream.of(5);
  
        stream.forEach(System.out::println);
    }
}

chevron_right


Output :

5

Example 3 : Singleton Long stream.

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java code for Stream.of()
// to get sequential Stream
// containing a single element.
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // creating a stream of Long
        // and printing sequential Stream
        // containing a single element
        Stream<Long> stream = Stream.of(4L);
  
        stream.forEach(System.out::println);
    }
}

chevron_right


Output :

4


My Personal Notes arrow_drop_up

In love with a semicolon because sometimes i miss it so badly)

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.