Optional

Java Joy: Optional orElse orElseGet That Is The Question

Posted on by  
Hubert Klein Ikkink

The Optional class has the orElse and orElseGet methods to return a value when the Optional object is empty. This is useful to return a default value for example. But there is a small difference between the two methods. The orElseGet method needs a Supplier argument that returns a value of the type of the Optional value. The Supplier is only invoked when the Optional value is empty. The statement passed as argument to the orElse method is always executed, even when the Optional value is not empty. Preferrably we should use orElseGet as it will only invoke statements if needed.

In the following example code we see when our method getDefaultGreeting is invoked by using orElse and orElseGet with an empty and non-empty Optional object:

Continue reading →

shadow-left