Currently whenever I need to create stream from an array, I do
String[] array = {"x1", "x2"};
Arrays.asList(array).stream();
Is there some direct way to create stream from an array?
arraysjavajava-8java-stream
Currently whenever I need to create stream from an array, I do
String[] array = {"x1", "x2"};
Arrays.asList(array).stream();
Is there some direct way to create stream from an array?
Best Answer
You can use Arrays.stream E.g.
You can also use
Stream.of
as mentioned by @fge , which looks likeBut note
Stream.of(intArray)
will returnStream<int[]>
whereasArrays.stream(intArr)
will returnIntStream
providing you pass an array of typeint[]
. So in a nutshell for primitives type you can observe the difference between 2 methods E.g.When you pass primitive array to
Arrays.stream
, the following code is invokedand when you pass primitive array to
Stream.of
the following code is invokedHence you get different results.
Updated: As mentioned by Stuart Marks comment The subrange overload of
Arrays.stream
is preferable to usingStream.of(array).skip(n).limit(m)
because the former results in a SIZED stream whereas the latter does not. The reason is thatlimit(m)
doesn't know whether the size is m or less than m, whereasArrays.stream
does range checks and knows the exact size of the stream You can read the source code for stream implementation returned byArrays.stream(array,start,end)
here, whereas for stream implementation returned byStream.of(array).skip().limit()
is within this method.