Early drafts of the API exposed methods like filter, map, and reduce on Collection or Iterable. However, user experience with this design led to a more formal separation of the “stream” methods into their own abstraction. Reasons included:
- Methods on
Collectionsuch asremoveAllmake in-place modifications, in contrast to the new methods which are more functional in nature. Mixing two different kinds of methods on the same abstraction forces the user to keep track of which are which. For example, given the declarationCollectionstrings; the two very similar-looking method calls
strings.removeAll(s -> s.length() == 0); strings.filter(s -> s.length() == 0); // not supported in the current APIwould have surprisingly different results; the first would remove all empty
Stringobjects from the collection, whereas the second would return a stream containing all the non-emptyStrings, while having no effect on the collection.Instead, the current design ensures that only an explicitly-obtained stream can be filtered:
strings.stream().filter(s.length() == 0)...;where the ellipsis represents further stream operations, ending with a terminating operation. This gives the reader a much clearer intuition about the action of
filter; -
With lazy methods added to
Collection, users were confused by a perceived—but erroneous—need to reason about whether the collection was in “lazy mode” or “eager mode”. Rather than burdeningCollectionwith new and different functionality, it is cleaner to provide aStreamview with the new functionality; -
The more methods added to
Collection, the greater the chance of name collisions with existing third-party implementations. By only adding a few methods (stream,parallel) the chance for conflict is greatly reduced; - A view transformation is still needed to access a parallel view; the asymmetry between the sequential and the parallel stream views was unnatural. Compare, for example
coll.filter(...).map(...).reduce(...);with
coll.parallel().filter(...).map(...).reduce(...);This asymmetry would be particularly obvious in the API documentation, where
Collectionwould have many new methods to produce sequential streams, but only one to produce parallel streams, which would then have all the same methods asCollection. Factoring these into a separate interface,StreamOpssay, would not help; that would still, counterintuitively, need to be implemented by bothStreamandCollection; - A uniform treatment of views also leaves room for other additional views in the future.

Leave a Reply