Java 8: how to filter out Optional.absent() items from a stream

I use java.util.Optional a lot.

Explicitly telling that a method might not return a result == no more null check == no more NullPointerException.

I also use streams a lot, here is a snippet that demonstrate how to filter out Optional.absent() values from a stream.

Arrays.asList(1, 2, 3, 4, 5)
  .stream()
  // Remove odd values
  .map(i -> i % 2 == 1 ? Optional.empty() : Optional.of("s"+i))
  // Remove empty items from the stream
  .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
  // Print to stdout
  .forEach(System.out::println);

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s