gpt4 book ai didi

java - Java 中 Stream.Builder 的用途是什么

转载 作者:行者123 更新时间:2023-12-04 00:14:26 25 4
gpt4 key购买 nike

换句话说,通过使用 Stream.Builder.add() 将项目添加到构建器然后使用 Stream.Builder.build() 我得到了什么>,与将项目添加到集合或数组中并从中创建流?

我假设在某些情况下某处会有好处,但对我来说并不明显......

最佳答案

假设机器有足够的内存,使用 Stream.Builder 允许向其添加超过 Integer.MAX_VALUE 的元素。

在内部,Stream.Builder 使用一个 SpinedBuffer,这是一个非公共(public)类。

来自 SpinedBuffer 文档:

An ordered collection of elements. Elements can be added, but not removed.Goes through a building phase, during which elements can be added, and atraversal phase, during which elements can be traversed in order but nofurther modifications are possible.

One or more arrays are used to store elements. The use of a multiplearrays has better performance characteristics than a single array used byArrayList, as when the capacity of the list needs to be increasedno copying of elements is required. This is usually beneficial in the casewhere the results will be traversed a small number of times.

因此,它也避免了 ArrayList 调整大小。

关于java - Java 中 Stream.Builder 的用途是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64917763/

25 4 0