How can I create a stream from an array?
Alternative to @sol4me's solution:
Stream.of(theArray)
Of the difference between this and Arrays.stream()
: it does make a difference if your array is of a primitive type. For instance, if you do:
Arrays.stream(someArray)
where someArray
is a long[]
, it will return a LongStream
. Stream.of()
, on the other hand, will return a Stream<long[]>
with a single element.
You can use Arrays.stream E.g.
Arrays.stream(array);
You can also use Stream.of
as mentioned by @fge , which looks like
public static<T> Stream<T> of(T... values) {
return Arrays.stream(values);
}
But note Stream.of(intArray)
will return Stream<int[]>
whereas Arrays.stream(intArr)
will return IntStream
providing you pass an array of type int[]
. So in a nutshell for primitives type you can observe the difference between 2 methods E.g.
int[] arr = {1, 2};
Stream<int[]> arr1 = Stream.of(arr);
IntStream stream2 = Arrays.stream(arr);
When you pass primitive array to Arrays.stream
, the following code is invoked
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
and when you pass primitive array to Stream.of
the following code is invoked
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
Hence you get different results.
Updated: As mentioned by Stuart Marks comment
The subrange overload of Arrays.stream
is preferable to using Stream.of(array).skip(n).limit(m)
because the former results in a SIZED stream whereas the latter does not. The reason is that limit(m)
doesn't know whether the size is m or less than m, whereas Arrays.stream
does range checks and knows the exact size of the stream
You can read the source code for stream implementation returned by Arrays.stream(array,start,end)
here, whereas for stream implementation returned by Stream.of(array).skip().limit()
is within this method.
Stream.of("foo", "bar", "baz")
Or, if you are already have an array, you can also do
Stream.of(array)
For primitive types use IntStream.of
or LongStream.of
etc.