I was wondering how stream().toArray[x -> new Integer[x]] knows what size of array to from? I wrote a snippet in which i created a list of an integer of size 4 and filtered the values and it created an array of length of the filtered stream, I could not see any method on stream to get a size of the stream.
List<Integer> intList = new ArrayList<Integer>();
intList.add(1);
intList.add(2);
intList.add(3);
intList.add(4);
Integer[] array = intList.stream()
.filter(x -> x > 2)
.toArray(x -> {
System.out.println("x --> " + x);
return new Integer[x];
});
System.out.println("array length: " + array.length);
Output of above code:
x --> 2
array length: 2
initially, the snippet was like
Integer[] array = intList.stream()
.filter(x -> x > 2)
.toArray(x -> new Integer[x]);
Just to get the understanding what value of x it passes i had to change it to print x in lambda
toArrayis a terminal operation. When you get totoArray, it evaluates the whole stream, and at that point knows how many items it has.count()x -> new Integer[x]you can writeInteger[]::new;)