Filtering a Stream of Optionals in Java – 在Java中过滤期权流

最后修改: 2016年 9月 25日

中文/混合/英文(键盘快捷键:t)

1. Introduction

1.介绍

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

在这篇文章中,我们将讨论如何从StreamOptionals中过滤掉非空的值。

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

我们将研究三种不同的方法–两种使用Java 8,一种使用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()

2.使用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:

Java 8中的一个选项是用Optional::isPresent过滤掉这些值,然后用Optional::get函数执行映射来提取值。

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

3. Using flatMap()

3.使用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:

另一个选择是使用flatMap和一个lambda表达式,将空的Optional转换为空的Stream实例,而将非空的Optional转换为只包含一个元素的Stream实例。

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:

另外,你可以采用同样的方法,用不同的方式将Optional转换为Stream

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

4. Java 9’s Optional::stream

4.Java 9的Optional::stream

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

随着Java 9的到来,所有这些都将变得相当简化,它为 Optional增加了一个stream()方法。

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:

这个方法类似于第3节中展示的方法,但这次我们使用一个预定义的方法将Optional实例转换为Stream实例。

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

无论Optional值是否存在,它都将返回一个由一个或零个元素组成的流。

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

5. Conclusion

5.结论

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

通过这个,我们很快就看到了从StreamOptionals中过滤现值的三种方法。

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

完整的实现代码样本可以在Github项目上找到。