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.
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 int
s 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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With