Is there a reason to use .flatMap(...)
over a combination of .filter(...)
and .map(...)
for Java Streams?
Using .flatMap(...)
can often be less readable than the combination of .filter(...)
and .map(...)
, so is there an advantage to using .flatMap(...)
?
For instance with an Optional
:
.flatMap(optional -> optional.isPresent() ? Stream.of(optional.get()) : Stream.empty())
or
.filter(optional -> optional.isPresent())
.map(optional -> optional.get())