Stream.of() with Array Elements
You'll learn how to create streams from arrays using Stream.of() and when to use it versus Arrays.stream().
When you have an array and want to convert it to a stream, you have two main options: Stream.of() and Arrays.stream(). While they might seem interchangeable, there's an important difference to understand.
How Stream.of() Works with Arrays
Stream.of() accepts a varargs parameter, which means you can pass individual elements OR an entire array. When you pass an array, Stream.of() treats it as a single element in the stream.
String[] words = {"Java", "Python", "Go"};
// Stream.of() with array - creates Stream<String>
Stream<String> stream1 = Stream.of(words);
stream1.forEach(System.out::println); // Java, Python, Go
// Equivalent to unpacking the array manually
Stream<String> stream2 = Stream.of("Java", "Python", "Go");
The Critical Difference for Primitive Arrays
Here's where it gets tricky. With primitive arrays, Stream.of() creates a stream containing the array as a single object, not a stream of the elements:
int[] numbers = {1, 2, 3};
// Stream.of() treats the array as ONE element
Stream<int[]> stream3 = Stream.of(numbers); // Stream of ONE array
stream3.forEach(arr -> System.out.println(arr.length)); // Prints: 3
// Arrays.stream() creates IntStream of elements
IntStream stream4 = Arrays.stream(numbers);
stream4.forEach(System.out::println); // 1, 2, 3
When to Use Which
- Use
Stream.of()when passing individual elements or object arrays - Use
Arrays.stream()when working with primitive arrays to get specialized streams (IntStream, LongStream, DoubleStream)
Key Takeaway: Stream.of() with an array creates a stream of the array's elements for object types, but wraps primitive arrays as single objects—use Arrays.stream() for primitive arrays to stream their elements.