How to get a stream from Optional class in Java 9?

JavaObject Oriented ProgrammingProgramming

The Optional class provides a container that may or may not contain a non-null value. It has been introduced in Java 8 to reduce the number of places in the code where a NullPointerException has generated. Java 9 added three methods: ifPresentOrElse(), or(), and stream(), which helps us deal with default values.

In the below example, we can get a stream from Optional class using Person class

Example

import java.util.Optional;
import java.util.stream.Stream;

public class OptionalTest {
   public static void main(String args[]) {
      getPerson().stream()
                 .map(Person::getName)
                 .map("Jai "::concat)
                 .forEach(System.out::println);

      getEmptyPerson().stream()
                      .map(Person::getName)
                      .map("Jai "::concat)
                      .forEach(System.out::println);
   }
   private static Optional<Person> getEmptyPerson() {
      return Optional.empty();
   }
   private static Optional<Person> getPerson() {
      return Optional.of(new Person("Adithya"));
   }
   static class Person {
      private String name;
      public Person(String name) {
         this.name = name;
      }
      public String getName() {
         return name;
      }
      public void setName(String name) {
         this.name = name;
      }
   }
}

Output

Jai Adithya
raja
Published on 27-Mar-2020 13:02:36
Advertisements