While developing my API that is not tied to any legacy code, I often find myself writing methods that are purely Streams pipeline terminated by collecting the results. Like this one:
ImmutableSet<T> deriveSomethingMeaningfulFromPrivateState() {
return myPrivateThingies.stream()
.map(this::ownerOfThing)
.map(Owner::socialStatus)
.filter(SocialStatus::isHeAFineMatey)
.collect(MyCustomCollectors.toImmutableSet());
}
Now, most of the clients of this class will usually need the Collection (in this case, an ImmutableSet) to search elements and iterate over it, but some clients may benefit from having a Stream so they could pipe some more operations on top of that Stream without the need to obtain a new stream from the Collection. So returning a Stream gives the cliens a superset of options they would have if they just had the Collection (after all, they can always collect()
the Stream themselves:
Stream<T> deriveSomethingMeaningfulFromPrivateState() {
return myPrivateThingies.stream()
.map(this::ownerOfthing)
.map(Owner::socialStatus)
.filter(SocialStatus::isHeAFineMatey);
// No collect
}
This approach is tempting for me to try out as I don't see any potential flaws it could have. However, I've never seen this approach in any library (probably becase there weren't many libraries released after the appearance of Java 8), so I'm a bit afraid to adopt it. Existing library classes usually return Collections when they derive something from the private state.
Is there something bad that could happen if I decide to return a Stream wherever my pre-Java-8 self would return a Collection? Or probably am I doing something of an antipattern here with all that deriving from private state?