Use of the Optional Stream Method in Java 9



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

Syntax

public Stream<T> stream()

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) {
      List<Optional<String>> list = Arrays.asList(
            Optional.empty(),
            Optional.of("TutorialsPoint"),
            Optional.empty(),
            Optional.of("Tutorix"));
      // If optional is non-empty, get the value in stream, otherwise return empty
      List<String> filteredListJava8 = list.stream()
            .flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())
            .collect(Collectors.toList());
      // Optional::stream method can return a stream of either one or zero element if data is present or not.
      List<String> filteredListJava9 = list.stream()
            .flatMap(Optional::stream)
            .collect(Collectors.toList());
      System.out.println(filteredListJava8);
      System.out.println(filteredListJava9);
   }
}

Output

[TutorialsPoint, Tutorix]
[TutorialsPoint, Tutorix]
Updated on: 2020-02-24T05:30:32+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements