Optional in Java 8: Part 1
In this lesson, we will look at the newly introduced Optional class. We will also look at different ways of creating an Optional.
What is an Optional
?
Java 8 has introduced a new class Optional<T>
in the java.util
package.
The Optional<T>
is a wrapper class that stores an object of type T
. The object may or may not be present in the optional.
According to Oracle, “Java 8 Optional
works as a container type for the value which is probably absent or null. Java Optional
is a final class present in the java.util package
.”
Let us look at how things worked before optional was introduced. In the below example, we have a getEmployee()
method which gets the employee object from a Map
. After fetching the employee object, we will print its details.
Get hands-on with 1200+ tech skills courses.