Home  >  Article  >  Java  >  What is the use of Optional.stream() method in Java 9?

What is the use of Optional.stream() method in Java 9?

WBOY
WBOYforward
2023-09-08 12:33:02654browse

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

In Java 9, the stream() method has been added to the Optional class to improve its functionality. stream()The method can be used to convert a Stream of Optional elements to a Stream with existing value elements. If Optional contains a value, returns a Stream containing that value. Otherwise, it returns an empty stream.

Syntax

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

Example

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);
   }
}

Output

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

The above is the detailed content of What is the use of Optional.stream() method in Java 9?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete