Difference between Stream.of() and Arrays.stream() method in Java

In this post, we will discuss the difference between Stream.of() and Arrays.stream() method in Java.


 

The Stream.of() and Arrays.stream() are two commonly used methods for creating a sequential stream from an specified array. Both these methods returns a Stream<T> when called with a non-primitive type T.

For instance, both Stream.of() and Arrays.stream() returns Stream<Integer> when called on an Integer array.

 
It is worth noting that Stream.of() method simply calls the Arrays.stream() method for non-primitive types as evident from the source code of Stream.of() method:

 
Well if Stream.of() is just a wrapper over the Arrays.stream() method, then why it is even included in Java? The answer to this question is highlighted when we use a primitive array.

 
1. For primitives arrays, Arrays.stream() and Stream.of() have different return types. For example if we pass an integer array, the Stream.of() method returns Stream<int[]> whereas Arrays.stream() returns an IntStream.

 

 
2. Since Stream.of() returns Stream<int[]> with integer array, we need to explicitly convert it into IntStream before consuming as shown below.

 
3. Arrays.stream() method is overloaded for primitive arrays of int, long, and double type. For other primitive types, Arrays.stream() won’t work. It returns IntStream for an int[] array, LongStream for a long[] array and DoubleStream for a double[] array. On the other hand, Stream.of() has no overloaded method for primitive arrays. Instead, it has below overloaded version which can take an Object:

 
Since arrays are also Objects in Java, above method will be invoked when we pass a primitive array to Stream.of().

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz