
- Java Tutorial
- Java - Home
- Java - Overview
- Java - Environment Setup
- Java - Basic Syntax
- Java - Object & Classes
- Java - Constructors
- Java - Basic Datatypes
- Java - Variable Types
- Java - Modifier Types
- Java - Basic Operators
- Java - Loop Control
- Java - Decision Making
- Java - Numbers
- Java - Characters
- Java - Strings
- Java - Arrays
- Java - Date & Time
- Java - Regular Expressions
- Java - Methods
- Java - Files and I/O
- Java - Exceptions
- Java - Inner classes
- Java Object Oriented
- Java - Inheritance
- Java - Overriding
- Java - Polymorphism
- Java - Abstraction
- Java - Encapsulation
- Java - Interfaces
- Java - Packages
- Java Advanced
- Java - Data Structures
- Java - Collections
- Java - Generics
- Java - Serialization
- Java - Networking
- Java - Sending Email
- Java - Multithreading
- Java - Applet Basics
- Java - Documentation
- Java Useful Resources
- Java - Questions and Answers
- Java - Quick Guide
- Java - Useful Resources
- Java - Discussion
- Java - Examples
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 Articles
- What are the new methods added to an Optional class in Java 9?
- Java 8 Optional Class
- How to use intermediate stream operations in JShell in Java 9?
- How to use terminal stream operations in JShell in Java 9?
- Optional property in a C# class
- How to use the collect() method in Stream API in Java 9?
- How to deserialize a Java object from Reader Stream using flexjson in Java?
- 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
- Get class from an object in Java
- How can we implement methods of Stream API in Java 9?
- How to get JShell documentation in Java 9?
- Java Program to retrieve a Stream from a List
- How to create a class and object in JShell in Java 9?

Advertisements