Stream.of() Method in Java
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
// 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.
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()andtoArray()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() 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.
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);
}
}
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.
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);
}
}
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[].
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);
}
}
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.
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);
}
}
[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 anull, which will fail in a lambda that calls a method on it. - Null array:
Stream.of((String[]) null)throwsNullPointerException; useStream.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
| Method | Input | Result | Use when |
|---|---|---|---|
Stream.of(a, b, c) | Individual values | Stream<T> | Values are written in code |
Stream.of(array) | Object array | Stream<T> | Works, but Arrays.stream() is clearer |
Arrays.stream(array) | Any array, also primitive | Stream<T> or IntStream etc. | You have an array, or need a range of it |
IntStream.of(1, 2, 3) | int values | IntStream | Fixed numbers, no boxing |
Stream.ofNullable(x) | One value or null | Zero or one element | A value that may be missing (Java 9) |
list.stream() | A collection | Stream<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:
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");
}
}
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 thanStream.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; uselist.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()orIntStream.of()for primitive arrays. - Use
Stream.ofNullable()for one value that may benull.
9. References
Frequently Asked Questions (FAQ)
Q1. What does Stream.of() do in Java?
Stream.of() is a static factory method added in Java 8 that creates a sequential, ordered stream from the values passed to it. Stream.of("a", "b") returns a Stream<String> with two elements.
Q2. What is the difference between Stream.of() and Arrays.stream()?
For object arrays they give the same stream. Arrays.stream() also accepts int[], long[] and double[], returning a primitive stream, and has overloads for a sub-range. Stream.of() with a primitive array returns a stream with one element: the array itself.
Q3. Can Stream.of() contain null?
Yes. Stream.of("a", null) creates a two-element stream including null. Passing a null array, as in Stream.of((String[]) null), throws NullPointerException. For a single value that may be null, use Stream.ofNullable(), added in Java 9.
Q4. Is the stream from Stream.of() ordered and sequential?
Yes. It is sequential, ordered in argument order and sized. Call parallel() if you need a parallel stream.
Q5. Why does Stream.of(list) not stream the list's elements?
Because the list is a single object, so it becomes the single element of the stream. Use list.stream(), or Stream.of(list1, list2).flatMap(List::stream) to stream the elements of several lists.