Java 9中的Optional.stream()方法有什么用途?

Java 9中的Optional.stream()方法有什么用途?

在Java 9中,stream()方法已添加到Optional 类中,以改进其功能。 stream()方法可用于将Optional元素的Stream转换为具有存在值元素的Stream。如果Optional 包含一个值,则返回包含该值的Stream。否则,它返回一个stream

语法

<strong>public Stream<T> stream()</strong>

示例

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class StreamMethodTest {
   public static void main(String[] args) {
     <strong> List<Optional<String>></strong> list = Arrays.asList(
            Optional.empty(),
            Optional.of("TutorialsPoint"),
            Optional.empty(),
            Optional.of("Tutorix"));
      <strong>// If optional is non-empty, get the value in stream, otherwise return empty</strong>
      <strong>List<String></strong> filteredListJava8 = list.stream()
            .<strong>flatMap</strong>(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
            .<strong>collect</strong>(Collectors.toList());
      <strong>// Optional::stream method can return a stream of either one or zero element if data is present or not.</strong>
      <strong>List<String></strong> filteredListJava9 = list.stream()
            .<strong>flatMap</strong>(<strong>Optional::stream</strong>)
            .<strong>collect</strong>(Collectors.toList());
      System.out.println(filteredListJava8);
      System.out.println(filteredListJava9);
   }
}

输出

<strong>[TutorialsPoint, Tutorix]
[TutorialsPoint, Tutorix]</strong>

以上就是Java 9中的Optional.stream()方法有什么用途?的详细内容,更多请关注其它相关文章!