2

I often find myself writing code like this:

return collectionOfOptionals.stream()
    .filter(Optional::isPresent)
    .map(Optional::get)
    .collect(toList());

But is there a way to compress those middle two lines into a single operation?

I can do this, but it feels even less satisfactory:

return collectionOfOptionals.stream()
    .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
    .collect(toList());
Peter Hall
  • 53,120
  • 14
  • 139
  • 204

1 Answers1

2

It seems that this is possible in Java 9, based on this question.

return collectionOfOptionals.stream()
    .flatMap(Optional::stream)
    .collect(toList());

This is much nicer. But what I have already will have to do in Java 8.

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
  • Even the `flatMap` is unnecessary, it is called a `flatten` operation that Java doesn't have. Java 8 half-a$$ed `Optional` can't be converted to a `Stream`, so... – Abhijit Sarkar Aug 15 '17 at 01:29