How to implement a Java stream?

The JDK’s standard implementation of Stream is the internal class, you cannot instantiate it directly.

Instead you can use,<T>, boolean) and various1, 2 other static factory methods to create an instance of the default implementation.

Using a spliterator is probably the most powerful approach as it allows you to provide objects lazily while also enabling efficient parallelization if your source can be divided into multiple chunks.

Additionally you can also convert streams back into spliterators, wrap them in a custom spliterator and then convert them back into a stream if you need to implement your own stateful intermediate operations – e.g. due to shortcomings in the standard APIs – since most available intermediate ops are not allowed to be stateful.
See this SO answer for an example.

In principle you could write your own implementation of the stream interface, but that would be quite tedious.

Leave a Comment