Stream.of() is a static factory method that creates a stream directly from a fixed set of values or an array, without needing to first wrap them in a collection.
Key Points: • Stream.of(T... values) accepts a varargs list of elements and returns a Stream<T> containing exactly those elements in order. • It's convenient for quickly testing a stream pipeline or working with a small, known set of values. • Stream.of() can also accept a single array argument, though for primitive arrays it treats the whole array as one element unless you use Arrays.stream() instead. • The resulting stream supports the full range of intermediate and terminal operations, just like a stream derived from a collection. • For an empty stream, Stream.empty() is used instead of calling Stream.of() with no arguments (which also works, but empty() is clearer intent).
Example: Stream.of("apple", "banana", "cherry").map(String::toUpperCase).forEach(System.out::println) turns three literal strings into a stream and prints each one in uppercase, with no list creation needed.
Code Example:
Stream.of(1, 2, 3, 4, 5)
.filter(n -> n % 2 == 0)
.forEach(System.out::println); // 2, 4Interview Tip: A concise interview answer is:
"Stream.of() takes a fixed set of values, typically as varargs, and wraps them directly into a Stream, so I don't have to build a List first just to get a stream going. It's handy for quick pipelines over a small, known set of elements, and it supports the same filter, map, and collect operations as any other stream."