What is the purpose of a Stream.Builder in Java

Viewed 448

To put it differently, what do I gain by using Stream.Builder.add() to add items to the builder and then using Stream.Builder.build(), versus adding the items in a collection or array and creating a Stream from that?

I assume there is a benefit somewhere in some circumstances but it's not obvious to me...

2 Answers

Assuming the machine has enough memory, using Stream.Builder allows to add more than Integer.MAX_VALUE elements to it.

Internally, Stream.Builder uses a SpinedBuffer, which is a non public class.

From SpinedBuffer docs:

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

One or more arrays are used to store elements. The use of a multiple arrays has better performance characteristics than a single array used by ArrayList, as when the capacity of the list needs to be increased no copying of elements is required. This is usually beneficial in the case where the results will be traversed a small number of times.

So, it also avoids ArrayList resizing.

It has a very interesting internal data structure that is highly optimized for insertions, without the possibility of removal or random access.

Your array and/or Collection pay an additional price for all other functionality that they support.

Related