Java 8 – Optional Class in java.util2 min read

Java

Overview

Another important addition made to Java 8 is Optional class. So, instead of directly referring null keyword, we can/must use available Optional class methods.

As quoted by Raoul-Gabriel Urma

Optional is like a container that either contains a value or not(it is then said to be “empty”), there is no concept of null here.

Required Import:

import java.util.Optional;

Let’s check out the available methods:

Please Note: In order to make use of Optional class methods, first we need to make our Object in question as an Optional Object.

1. Value check with isPresent()

When we want to check if an Optional object has a value in it or not, we can use isPresent() method.

Optional opt = Optional.of("blogItWithSatyam");
System.out.print(opt.isPresent());
output: true

2. Conditional check with ifPresent()

If we want to do an action post validation, then we can use this method, for example:
Print String “blogItWithSatyam” only if it’s not null, check the code below;

Optional opt1 = Optional.of("blogItWithSatyam");
opt1.ifPresent(String -> System.out.println(String));
output: blogItWithSatyam

3. get()

This method is simply used to get the value that the Optional object is holding.

Optional o = Optional.of("abc");
System.out.println(o.get());
output: abc

4. ofNullable()

This method returns the same input Optional object if the input is not null

Optional opt2 = Optional.ofNullable("abc");
System.out.println(opt2.get());
output: abc

For a null input, it returns a java.util.NoSuchElementException exception, as shown below:

Optional opt2 = Optional.ofNullable(null);
System.out.println(opt2.get());

4. orElse() and orElseGet

There is a slight difference between these two, both return the same input value if present, and if it’s not present; orElse() returns the set default value, Whereas, orElseGet() returns the result of the invoked supplier functional interface.

Using orElse(): Here, the default set value is “blogitWithSatyam”

String nullValue1 = null;
String v1 = Optional.ofNullable(nullValue1)
           .orElse("blogItWithSatyam");		
System.out.println(v1);
output: blogItWithSatyam

Using orElseGet(): Here, the default set value is through a functional interface implementation that returns a String “blogItWithSatyam”.

String nullValue2 = null;
String v2 = Optional.ofNullable(nullValue2)
           .orElseGet(() -> "blogItWithSatyam");
System.out.println(v2);
output: blogItWithSatyam

Conclusion

In this quick article, we looked at the usages and implementations of various methods of the Optional class. To know more about the changes that are done to the Optional class in JDK 9.0, click here

As always, the code is available on Github

One thought on “Java 8 – Optional Class in java.util2 min read

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.