Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.stream(array) vs Arrays.asList(array).stream()

In this question it has already been answered that both expressions are equal, but in this case they produce different results. For a given int[] scores, why does this work:

Arrays.stream(scores)
        .forEach(System.out::println);

...but this does not:

Arrays.asList(scores).stream()
        .forEach(System.out::println);

As far as I know .stream() can be called on any Collection, which Lists definitely are. The second code snippet just returns a stream containing the array as a whole instead of the elements.

like image 498
AdHominem Avatar asked May 16 '16 11:05

AdHominem


2 Answers

The reason the second code snippet does not work is that there is no such thing as List<int> in Java. That is why Arrays.asList(scores) does not produce what you expect.

Switching from int[] to Integer[] would fix this problem, in the sense that the two pieces of code would produce identical results. However, your code would be less efficient, because all ints would be boxed.

In fact, efficiency is the reason behind having overloads of stream for primitive arrays. Your call Arrays.stream(scores) is routed to stream(int[] array), producing IntStream object. Now you can apply .forEach(System.out::println), which calls println(int), again avoiding boxing.

like image 52
Sergey Kalinichenko Avatar answered Sep 21 '22 20:09

Sergey Kalinichenko


Arrays.asList expects arrays of Object not arrays of primitives. It does not complain on compile time because arrays of primitive is an object.

It can take one object as list but what is inside that object(arrays of primitive is an object) cannot be convert to list.

Arrays of primitive can be convert to stream using IntStream,DoubleStream and LongStream

like this

double[] doubleArray = {1.1,1.2,1.3};

DoubleStream.of(doubleArray).forEach(System.out::println);


int[] intArray = {1,2,3,4,5,6};

IntStream.of(intArray).forEach(System.out::println);


long[] longArray = {1L,2L,3L};

LongStream.of(longArray).forEach(System.out::println);
like image 34
Noor Nawaz Avatar answered Sep 21 '22 20:09

Noor Nawaz