问题描述
我想知道stream()。toArray [x - > new Integer [x]]如何知道来自哪个数组的大小?我写了一个片段,其中我创建了一个大小为4的整数列表并过滤了这些值,它创建了一个长度为过滤流的数组,我无法看到任何方法来获取流的大小。
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);
上述代码的输出:
x --> 2
array length: 2
最初,该片段就像
Integer[] array = intList.stream()
.filter(x -> x > 2)
.toArray(x -> new Integer[x]);
为了理解它传递的x值,我必须将其更改为在lambda中打印x
Just to get the understanding what value of x it passes i had to change it to print x in lambda
推荐答案
当然,这取决于实现。对于某些流,如果源具有已知大小且不涉及大小改变中间操作,则大小是可预测的。由于您使用的是过滤器
操作,因此不适用,但是,根据未过滤的计数,存在估计大小。
Of course, this is implementation dependent. For some streams, the size is predicable, if the source has a known size and no size changing intermediate operation is involved. Since you are using a filter
operation, this doesn’t apply, however, there is an estimate size, based on the unfiltered count.
现在,Stream实现只是分配一个临时缓冲区,使用估计的大小或默认大小,并在必要时支持增加容量,并将数据复制到由您的函数创建的目标数组中,最后一步。
Now, the Stream implementation simply allocates a temporary buffer, either using the estimated size or a default size with support for increasing the capacity, if necessary, and copies the data into the destination array, created by your function, in a final step.
可以通过提供的函数创建中间缓冲区,这就是为什么声明... 使用提供了生成器函数来分配返回的数组,以及分区执行或调整大小所需的任何其他数组我依稀记得在早期版本中看到这样的行为。但是,当前实现只在)用于中间存储并仅使用提供的函数来创建最终数组。因此,在给定此特定JRE实现的情况下,您无法使用该函数观察中间数组的创建。
The intermediate buffers could be created via the supplied function, which is the reason why the documentation states "…using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing" and I vaguely remember seeing such a behavior in early versions. However, the current implementation just uses Object[]
arrays (or Object[][]
in a "spined buffer") for intermediate storage and uses the supplied function only for creating the final array. Therefore, you can’t observe intermediate array creation with the function, given this specific JRE implementation.
这篇关于Java 8流的toArray和size参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!