Or() methods of Optional object in Java

The Optional object in Java has three methods with name start with or(). In this tutorial, we will together learn about them and what is the difference between them.

First, I might mention the orElse() method.

This method is used to return a default value in case our Optional object is empty.

The parameter of this method is the default value that will be returned.

For example:

Result:

Or() methods of Optional object in Java


The second or() method I want to talk about is the orElseGet() method of the Optional object.

The parameter of this method is a Functional Interface Supplier. You can see more information about the Supplier interface here.

The purpose of this method is the same as the orElse() method, but in this case, the default value returned from the Functional Interface Supplier.

For example:

Result:

Or() methods of Optional object in Java


The third method is the or() method.

This method was introduced from Java 9.

The parameter of this method is also a Functional Interface Supplier.

This method always gives us an Optional object that is not empty. If the Optional object is not empty, it returns the Optional object itself, otherwise, it returns the Optional object that the Supplier creates.

For example:

Result:

Or() methods of Optional object in Java

 

Add Comment