Why Iam getting different value when iam using Arrays.stream and Stream.of ideally both should return same value
i/p:
int num[]= {1,2,3,4};
System.out.println(Arrays.stream(num).count());
o/p:
4
i/p:
int num[]= {1,2,3,4};
System.out.println(Stream.of(num).count());
o/p:
1
Take a look at the code of Arrays.stream
and Stream.of
to understand more:
public static IntStream stream(int[] array) {
return stream(array, 0, array.length);
}
Arrays.stream in one of signatures take an int[]
and split the value in this array for that you got 4.
But
public static<T> Stream<T> of(T t) {
return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
}
took an Object of type T for that int[]
is considered as one unity, so for example if you use:
Stream.of(new int[]{1, 2, 3}, new int[]{4, 5}).count()
You will get 2.
to get the same result of Arrays.stream
you can use flatMapToInt
after the of(..)
:
Stream.of(num2).flatMapToInt(Arrays::stream).count()
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