Filtering a Stream of Optionals in Java

1. Introduction

In this article, we’re going to talk about how to filter out non-empty values from a Stream of Optionals.

We’ll be looking at three different approaches – two using Java 8 and one using the new support in Java 9.

We will be working on the same list in all examples:

List<Optional<String>> listOfOptionals = Arrays.asList(
  Optional.empty(), Optional.of("foo"), Optional.empty(), Optional.of("bar"));

2. Using filter()

One of the options in Java 8 is to filter out the values with Optional::isPresent and then perform mapping with the Optional::get function to extract values:

List<String> filteredList = listOfOptionals.stream()
  .filter(Optional::isPresent)
  .map(Optional::get)
  .collect(Collectors.toList());

3. Using flatMap()

The other option would be to use flatMap with a lambda expression that converts an empty Optional to an empty Stream instance, and non-empty Optional to a Stream instance containing only one element:

List<String> filteredList = listOfOptionals.stream()
  .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
  .collect(Collectors.toList());

Alternatively, you could apply the same approach using a different way of converting an Optional to Stream:

List<String> filteredList = listOfOptionals.stream()
  .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
  .collect(Collectors.toList());

4. Java 9’s Optional::stream

All this will get quite simplified with the arrival of Java 9 that adds a stream() method to Optional.

This approach is similar to the one showed in section 3 but this time we are using a predefined method for converting Optional instance into a Stream instance:

It will return a stream of either one or zero element(s) whether the Optional value is or isn’t present:

List<String> filteredList = listOfOptionals.stream()
  .flatMap(Optional::stream)
  .collect(Collectors.toList());

5. Conclusion

With this, we’ve quickly seen three ways of filtering the present values out of a Stream of Optionals.

The full implementation of code samples can be found on the Github project.

Related posts:

Introduction to Spring Boot CLI
Guide to Apache Commons CircularFifoQueue
Biểu thức Lambda trong Java 8 – Lambda Expressions
Spring Security – Reset Your Password
Spring Boot - Application Properties
Java Program to Implement Control Table
Guide to @JsonFormat in Jackson
Java Program to Implement the Schonhage-Strassen Algorithm for Multiplication of Two Numbers
Java Program to implement Circular Buffer
Chuyển đổi giữa các kiểu dữ liệu trong Java
Java Program to Give an Implementation of the Traditional Chinese Postman Problem
Java Program to Check if a Given Set of Three Points Lie on a Single Line or Not
Java Program to Implement VList
Introduction to Spliterator in Java
Java Program to Implement Pairing Heap
Java Program to Find Maximum Element in an Array using Binary Search
Merging Streams in Java
Java Program to Perform Complex Number Multiplication
Using Custom Banners in Spring Boot
OAuth2 for a Spring REST API – Handle the Refresh Token in Angular
Java Program to Check Whether an Input Binary Tree is the Sub Tree of the Binary Tree
Truyền giá trị và tham chiếu trong java
Practical Java Examples of the Big O Notation
Quick Intro to Spring Cloud Configuration
Lập trình đa luồng với CompletableFuture trong Java 8
The Spring @Controller and @RestController Annotations
Java Program to Implement CountMinSketch
Java Program to Check Whether an Undirected Graph Contains a Eulerian Cycle
Jackson – Marshall String to JsonNode
Java Program to Implement Network Flow Problem
Java Program to Implement Self Balancing Binary Search Tree
Java Program to Implement Red Black Tree