2

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())
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
SBylemans
  • 1,764
  • 13
  • 28

1 Answers1

4

I, along with the Java language architects, agree with you that Stream#flatMap for a Stream<Optional<T>> isn't readable in Java 8, which is why they introduced Optional#stream in Java 9.

Using this, your code becomes much more readable:

.flatMap(Optional::stream)
Jacob G.
  • 28,856
  • 5
  • 62
  • 116