 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get a stream from Optional class in Java 9?
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
Advertisements
 