How can I create a stream from an array?

adam.kubi picture adam.kubi · Jan 11, 2015 · Viewed 63k times · Source

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?

Answer

sol4me picture sol4me · Jan 11, 2015

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.