Introduction
Java 8 has many new features, one of them is the Optional monad. Optional has two methods ‘orElse’ and ‘orElseGet’ they are very similar and can create confusion for the developers. In the article, we will try to understand the difference between the two.
Syntax
orElse
orElseGet
Exploring the Difference
orElseGet: The 'orElseGet' will execute the Supplier function only if the value is not present in the Optional.
The code above returns “TEST” and the ‘none()’ function will not be executed. Now instead of “TEST” pass null,
Since the value is missing in this case, the ‘none()’ function will be executed and a String ‘NONE’ returned, the output is
Inside None
NONE
The 'orElseGet' will execute the ‘none’ function only when the value is not present.
orElse: The ‘orElse’ will execute the ‘none’ function, irrespective of the value is present or not,
The orElse, executes the ‘none’ function, although the value is present, the program.
Output in this case is,
Inside none
TEST
with null,
Output
Inside none
NONE
If the Optional doesn’t contain a value, both orElse and orElseGet are the same, but if the value is present then orElse will execute the ‘none()’ function in both cases if we are working with List or any other collection with Optional, the execution of ‘orElse’ will be an expensive one if we are trying to create objects inside it, then it will create as many objects as the size of the Collection.
Thank You.