

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
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
- Related Questions & Answers
- Java 8 Optional Class
- What are the new methods added to an Optional class in Java 9?
- Optional property in a C# class
- How to use terminal stream operations in JShell in Java 9?
- How to use intermediate stream operations in JShell in Java 9?
- How to use the collect() method in Stream API in Java 9?
- How can we implement methods of Stream API in Java 9?
- How to get JShell documentation in Java 9?
- When to use the ofNullable() method of Stream in Java 9?
- Java Program to retrieve a Stream from a List
- Get all declared fields from a class in Java
- Get a value from Unit Tuple class in Java
- Get a value from Pair Tuple class in Java
- How to create a class and object in JShell in Java 9?
- Get class from an object in Java
Advertisements