The difference is pretty subtle and if you dont pay much attention then you will keep it using in a wrong way.
Best way to understand the difference between orElse()
and orElseGet()
is that orElse()
will always be executed if the Optional<T>
is null or not, But orElseGet()
will only be executed when Optional<T>
is null.
The dictionary meaning of orElse is :- execute the part when something is not present, but here it contradicts, see the below example:
Optional<String> nonEmptyOptional = Optional.of("Vishwa Ratna");
String value = nonEmptyOptional.orElse(iAmStillExecuted());
public static String iAmStillExecuted(){
System.out.println("nonEmptyOptional is not NULL,still I am being executed");
return "I got executed";
}
Output: nonEmptyOptional is not NULL,still I am being executed
Optional<String> emptyOptional = Optional.ofNullable(null);
String value = emptyOptional.orElse(iAmStillExecuted());
public static String iAmStillExecuted(){
System.out.println("emptyOptional is NULL, I am being executed, it is normal as
per dictionary");
return "I got executed";
}
Output: emptyOptional is NULL, I am being executed, it is normal as per dictionary
For
orElseGet()
, The method goes as per dictionary meaning, TheorElseGet()
part will be executed only when the Optional is null.
Benchmarks:
+--------------------+------+-----+------------+-------------+-------+
| Benchmark | Mode | Cnt | Score | Error | Units |
+--------------------+------+-----+------------+-------------+-------+
| orElseBenchmark | avgt | 20 | 60934.425 | ± 15115.599 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
| orElseGetBenchmark | avgt | 20 | 3.798 | ± 0.030 | ns/op |
+--------------------+------+-----+------------+-------------+-------+
Remarks:
orElseGet()
has clearly outperformedorElse()
for our particular example.
Hope it clears the doubts of people like me who wants the very basic ground example :)