In order to keep implementation details from leaking, instead of returning, e.g., a Collection<MyCoolObject>
, one might implement Iterable<MyCoolObject>
, which would then require implementing Iterator<T>
from the Iterable
Interface. Thus however the internal data structure is managed, the access to the elements is via the Iterator
.
With Java 8, one might wish to add Stream<MyCoolObject> stream()
to MyCoolObject
. (See also: recommendation to support stream
in the book Java 8 Lambdas). While adding the method isn't difficult (and I did read the Question about Why Iterable Doesn't Provide Stream), it seems odd that Java did not add an Interface for Streamable<T>
to mirror the Iterable<T>
idea. (Well, a different name perhaps since Streamable
exists for the ever use CORBA stuff).
I think I followed the Answer about why adding Stream
to Iterable
was potentially problematic, but I do not see why a Streaming<T>
interface couldn't have been provided. For example, Collections
could have implemented the Streaming<T>
interface, and it would make it clearer for other objects that one could expect a stream()
method.
Based upon an Answer to the above referenced Question, it is possible to get a Stream
from the Iterable
via
Stream s = StreamSupport.stream(iter.spliterator(), false);
but that seems like a lot of work given that MyObject
could would like to just implement stream()
to allow a user of the object to do
myObject.stream().filter(...).collect(...)
without the intervening conversion from the iterator.
Is there a reason for the lack of an interface for streaming capable objects? Is there a better approach than just implementing stream()
on MyCoolObject and letting someone look through the Javadoc so they know it has a stream()
method?
Or, is quite likely, am I misunderstanding something about the approach for Stream?
(Also, I implement stream()
in CoolObject, but then forget to implement parallelStream()
, which is something that would be alleviated by having the interface).