Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement a Java stream?

I want to implement a Stream<T>.

I don't want to just use implements Stream<T>, because I would have to implement a ton of methods.

Can this be avoided?

To be more concrete, how can I stream t1, t2 and t3 for example:

class Foo<T> {     T t1, t2, t3;      Foo(T t1, T t2, T t3) {         this.t1 = t1;         this.t2 = t2;         this.t3 = t3;     } } 
like image 852
clankill3r Avatar asked Jun 06 '15 17:06

clankill3r


People also ask

How are Java streams implemented?

Since JDK 8, a spliterator method has been included in every collection, so Java Streams use the Spliterator internally to iterate through the elements of a Stream. Java provides implementations of the Spliterator interface, but you can provide your own implementation of Spliterator if for whatever reason you need it.

How are streams implemented?

In object-oriented programming, input streams are generally implemented as iterators. In the Scheme language and some others, a stream is a lazily evaluated or delayed sequence of data elements. A stream can be used similarly to a list, but later elements are only calculated when needed.

Which class implements stream interface in Java?

The JDK's standard implementation of Stream is the internal class java. util.

How streams are executed in Java?

Streams are pull-based. Only a terminal operations (like the collect ) will cause items to be consumed. Conceptually this means that collect will ask an item from the limit , limit from the map and map from the filter , and filter from the stream. And this conforms to your first printout.


1 Answers

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<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.

like image 101
the8472 Avatar answered Sep 29 '22 09:09

the8472