00:00

Stream.of() Method in Java

Last updated:

Stream.of() is a static factory method of the java.util.stream.Stream interface, available since Java 8, that creates a sequential, ordered stream from the values you pass to it. It is a stream creation operation: it builds the source of a pipeline, and you then add intermediate and terminal operations.

Use it when the elements are known in your code, such as a few status codes, test data or a fixed set of options. This tutorial covers both overloads, how arrays are handled, the null pitfalls, and how it compares with Arrays.stream() and Stream.ofNullable().

1. Syntax and Method Signature

Stream.java (API)
// java.util.stream.Stream (Java 8)
static <T> Stream<T> of(T t)                  // a stream with exactly one element

@SafeVarargs
static <T> Stream<T> of(T... values)          // a stream of the given values, in order

T is the element type, inferred from the arguments. The varargs version receives the values as an array and is equivalent to Arrays.stream(values). Both return a Stream<T>; no functional interface is involved.

Usage
Stream<String> statuses = Stream.of("NEW", "PAID", "SHIPPED");
Stream<Integer> single  = Stream.of(42);

2. How Stream.of() Works

The single-argument version wraps one value. The varargs version takes the array that Java creates for the arguments and streams over it, exactly like Arrays.stream(). The resulting stream is:

  • Sequential until you call parallel().
  • Ordered: elements come out in the order you wrote them.
  • Sized: the number of elements is known up front, which lets operations such as count() and toArray() work efficiently.

Like every stream source, Stream.of() is lazy in the sense that it only describes the elements; nothing is processed until a terminal operation runs.

Stream.of() turns fixed values into an ordered stream Four values, NEW, PAID, SHIPPED and DELIVERED, are passed to Stream.of. The result is a stream with the same four elements in the same order. VALUES "NEW" "PAID" "SHIPPED" "DELIVERED" Stream.of(values...) STREAM NEW PAID SHIPPED DELIVERED
Figure 1: Stream.of() keeps the values in argument order. The resulting stream is sequential, ordered and sized.

3. Java Examples

Example 1: Stream a few fixed values

Print the order statuses that a shipment can move through, in upper case with arrows between them.

OrderStatusFlow.java
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class OrderStatusFlow {

    public static void main(String[] args) {
        String flow = Stream.of("new", "paid", "packed", "shipped", "delivered")
                .map(String::toUpperCase)
                .collect(Collectors.joining(" -> "));

        System.out.println(flow);
    }
}
Output
NEW -> PAID -> PACKED -> SHIPPED -> DELIVERED

How it works: The values keep the order in which they were written, which matters here because the output describes a sequence of states.

Example 2: Mixing a few objects in one stream (Java 16+)

A checkout page shows three fixed shipping options. Find the cheapest one that delivers within three days.

ShippingOptions.java
import java.util.Comparator;
import java.util.stream.Stream;

public class ShippingOptions {

    record Option(String name, int days, int price) { }

    public static void main(String[] args) {
        String best = Stream.of(
                        new Option("Standard", 5, 40),
                        new Option("Express", 2, 120),
                        new Option("Priority", 3, 90))
                .filter(option -> option.days() <= 3)
                .min(Comparator.comparingInt(Option::price))
                .map(Option::name)
                .orElse("none");

        System.out.println("Cheapest fast option: " + best);
    }
}
Output
Cheapest fast option: Priority

How it works: Stream.of() builds the stream directly from object literals, so no temporary list is needed. min() returns an Optional, which map() and orElse() unwrap safely.

Example 3: An object array is spread, a primitive array is not

Show what Stream.of() does with a String[] and with an int[].

StreamOfArrays.java
import java.util.Arrays;
import java.util.stream.Stream;

public class StreamOfArrays {

    public static void main(String[] args) {
        String[] cities = {"Surat", "Mysuru", "Shillong"};
        long cityCount = Stream.of(cities).count();
        System.out.println("Stream.of(String[]) elements: " + cityCount);

        int[] scores = {70, 85, 92};
        long scoreCount = Stream.of(scores).count();
        System.out.println("Stream.of(int[]) elements:    " + scoreCount);

        int total = Arrays.stream(scores).sum();
        System.out.println("Arrays.stream(int[]) sum:     " + total);
    }
}
Output
Stream.of(String[]) elements: 3
Stream.of(int[]) elements:    1
Arrays.stream(int[]) sum:     247

How it works: A String[] matches the T... parameter, so each string becomes an element. An int[] cannot be a T[] because T must be a reference type, so Java treats the whole array as one element and returns a Stream<int[]>. Use Arrays.stream() or IntStream.of() for primitive arrays.

Example 4: Combining a few sources into one stream (Java 9+)

Merge the error codes reported by three services, removing duplicates and sorting them.

MergeErrorCodes.java
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MergeErrorCodes {

    public static void main(String[] args) {
        List<String> payments = List.of("E42", "E07");
        List<String> inventory = List.of("E13", "E42");
        List<String> shipping = List.of("E07", "E99");

        List<String> allCodes = Stream.of(payments, inventory, shipping)
                .flatMap(List::stream)
                .distinct()
                .sorted()
                .collect(Collectors.toList());

        System.out.println(allCodes);
    }
}
Output
[E07, E13, E42, E99]

How it works: Stream.of() creates a stream of three lists, and flatMap(List::stream) flattens them into one stream of codes. This is a tidy alternative to nesting several Stream.concat() calls.

4. Real-World Use Cases

  • Configuration and enums of strings: streaming a small, fixed set of feature flags, report columns or currency codes.
  • Unit tests: building test inputs inline, such as Stream.of(order1, order2, order3), without creating a list first.
  • Combining sources: Stream.of(listA, listB, listC).flatMap(List::stream) merges several collections cleanly.

5. Important Points

  • Empty call: Stream.of() with no arguments returns an empty stream.
  • Null elements are allowed: Stream.of("a", null) contains a null, which will fail in a lambda that calls a method on it.
  • Null array: Stream.of((String[]) null) throws NullPointerException; use Stream.ofNullable() (Java 9) for a single value that may be null.
  • Duplicates are kept; add distinct() to remove them.
  • Shared array: the varargs version streams over the array itself, so changing that array before the terminal operation changes the elements seen.

6. Stream.of() vs Related Methods

MethodInputResultUse when
Stream.of(a, b, c)Individual valuesStream<T>Values are written in code
Stream.of(array)Object arrayStream<T>Works, but Arrays.stream() is clearer
Arrays.stream(array)Any array, also primitiveStream<T> or IntStream etc.You have an array, or need a range of it
IntStream.of(1, 2, 3)int valuesIntStreamFixed numbers, no boxing
Stream.ofNullable(x)One value or nullZero or one elementA value that may be missing (Java 9)
list.stream()A collectionStream<E>Data is already in a collection

7. Common Mistakes and Best Practices

Passing a primitive array

Stream.of(intArray) gives a stream with a single int[] element, as Example 3 shows. Use Arrays.stream(intArray) or IntStream.of(intArray).

Passing a value that may be null

If a method returns null for "no value", wrapping it with Stream.of() puts a null element into the stream. Stream.ofNullable() returns an empty stream instead:

OfNullableFix.java
import java.util.stream.Stream;

public class OfNullableFix {

    static String findCoupon(String user) {
        return user.equals("vip") ? "SAVE20" : null;
    }

    public static void main(String[] args) {
        long wrong = Stream.of(findCoupon("guest")).count();
        long right = Stream.ofNullable(findCoupon("guest")).count();

        System.out.println("Stream.of(null value):         " + wrong + " element");
        System.out.println("Stream.ofNullable(null value): " + right + " elements");
    }
}
Output
Stream.of(null value):         1 element
Stream.ofNullable(null value): 0 elements

Other mistakes to avoid

  • Building a list just to stream it. Arrays.asList(a, b).stream() is longer than Stream.of(a, b).
  • Using Stream.of() for large data. It is for values in code; large data normally already lives in a collection or array.
  • Expecting Stream.of(list) to stream the list's elements. It creates a stream with one element, the list; use list.stream().

8. Summary

  • Stream.of() creates a sequential, ordered, sized stream from values written in code.
  • An object array is spread into elements; a primitive array becomes a single element.
  • Use Arrays.stream() or IntStream.of() for primitive arrays.
  • Use Stream.ofNullable() for one value that may be null.

9. References