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

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

WBOY
Release: 2023-09-08 12:33:02
forward
680 people have browsed it

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>
Copy after login

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);
   }
}
Copy after login

Output

<strong>[TutorialsPoint, Tutorix]
[TutorialsPoint, Tutorix]</strong>
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template