Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arrays.Stream vs Stream.of

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
like image 476
Saipriyadarshini Bandi Avatar asked Sep 19 '25 16:09

Saipriyadarshini Bandi


1 Answers

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()
like image 79
YCF_L Avatar answered Sep 21 '25 13:09

YCF_L