Closed stickfigure closed 3 years ago
To give a real-world example of some code I'm trying to improve:
return StreamEx.of(shop.getLanguages())
.map(Language::valueOfOpt)
.filter(Optional::isPresent)
.map(Optional::get)
.map(lang -> getListingTranslation(shopId, listingId, lang))
.filter(Optional::isPresent)
.map(Optional::get)
.toImmutableList();
can you use java 9?
Not yet (for a variety of Google App Engine related reasons). But in Java 9, what's the idiom that cleans this up?
in j9 there is Optional.stream so you can do someStreamOfOptionals.flatmap(optional::stream)
Adding .present()
is not very good idea, as this method will be available for any stream, not just stream of optional, and its meaning will be confusing. People may accidentally call it expecting some different behavior. The same behavior is already provided with .mapPartial(fn)
method, so you can use
streamOfOptionals.mapPartial(x -> x) // or use Function.identity()
Another (though possibly less performant) way to achieve this is to use StreamEx.of(Optional)
:
streamOfOptionals.flatMap(StreamEx::of)
This solution could be useful if the streamOfOptionals
is not StreamEx object but a classic JDK stream.
Your bigger sample could be reduced to:
return StreamEx.of(shop.getLanguages())
.mapPartial(Language::valueOfOpt)
.mapPartial(lang -> getListingTranslation(shopId, listingId, lang))
.toImmutableList();
Looks like mapPartial is exactly what I am looking for, thanks!
I find myself doing this a lot when working with streams of optionals:
This boilerplate seems common enough that it would be convenient to have a
present()
method:Thoughts?