How to implement a Java stream?

后端 未结 5 894
悲哀的现实
悲哀的现实 2020-12-01 06:34

I want to implement a Stream.

I don\'t want to just use implements Stream, because I would have to implement a ton of met

5条回答
  •  北海茫月
    2020-12-01 06:59

    The JDK's standard implementation of Stream is the internal class java.util.stream.ReferencePipeline, you cannot instantiate it directly.

    Instead you can use java.util.stream.Stream.builder(), java.util.stream.StreamSupport.stream(Spliterator, 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.

提交回复
热议问题