Course contentsShow
← Java
Lesson 1374 of 2,87031. Streams API: Creation and BasicsFree lesson

Stream.of() for Fixed Elements

Create streams from explicit values using Stream.of(), understanding varargs and single-element streams.

Stream.of() for Fixed Elements

You'll learn how to create streams directly from a handful of known values using Stream.of().

When you need a stream containing a few specific elements—say, three strings or five numbers—you don't need to build a collection first. The Stream.of() factory method lets you pass values directly and get a stream ready to go.

The Core Idea

Stream.of() is a static factory method that accepts a variable number of arguments (varargs) and returns a stream containing exactly those elements, in order. Think of it like ordering a custom pizza: you specify exactly the toppings you want, and that's what you get—no more, no less.

Stream<String> fruits = Stream.of("apple", "banana", "cherry");

This creates a stream with three elements. You can pass any number of arguments:

Stream<Integer> numbers = Stream.of(10, 20, 30, 40, 50);
Stream<String> single = Stream.of("lonely");

Understanding Varargs

Behind the scenes, Stream.of() uses Java's varargs feature. The signature looks like:

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

The T... means "zero or more arguments of type T." Java bundles these into an array internally, but you write them as comma-separated values—much cleaner than manually creating an array.

Single-Element Streams

You can create a stream with just one element:

Stream<String> oneItem = Stream.of("solo");

This is perfectly valid and useful when you need uniform stream-based processing for both single and multiple values.

Key Takeaway:
Stream.of() is the simplest way to create streams from explicit values, accepting any number of comma-separated arguments and producing a sequential stream in that exact order.