Jan Hettich
Jan Hettich

Reputation: 9886

How to easily make custom Stream class in Java (like with Ruby Enumerable)

In Ruby, if you mix the Enumerable module into your own custom collection class, you only have to implement the each method, and all the methods of Enumerable (map, select, reduce, etc.) become available on your own class.

In Java 8, does the class library have an interface or abstract class that you can inherit from, such that you only have to override a single method to create your own Stream class? I could generate a Stream<T> instance by using Stream<T>.generate or Stream.Builder<T>, but I would like to be able create a custom Stream class (without having to do a lot of work).

Upvotes: 0

Views: 1034

Answers (1)

Bernd Ebertz
Bernd Ebertz

Reputation: 1327

I think inheritance isn't the approach Streams are designed for in Java. So you'd rather to implement the Spliterator interface and create a stream upon your data presented via such a Spliterator and then build your stream via

StreamSupport.stream(data, parallel);

This way you can provide pretty specific forms of data as a stream without copying all the data into the stream as it's necessary with the methods you mentioned. But if you really need to overwrite some of the stream behaviors thing get pretty weird. So hopefully that's not actually what you need.

Upvotes: 1

Related Questions