Java Optional orElse Vs. OrEleseGet (with Examples)

Introduced in Java 8, the Optional class acts as a container object that may or may not contain a non-null value. It is considered as a best practice against returning a null value from a method and protects from the deadly NullPointerException errors.

Rather than checking the presence of a value in an Optional instance, we can also specify a default value that will be returned if the Optional is empty. Its two methods orElse() and OrEleseGet() do exactly the same and return a default value if the Optional contains null.

Optional<String> optional = Optional.ofNullable(null);

String resultOrElse = optional.orElse("Default Value");		
String resultOrElseGet = optional.orElseGet(() -> generateDefaultValue());

public static String generateDefaultValue() {
  System.out.println("Doing some work");
  return "Default Value";
}
FeatureorElse()orElseGet()
Evaluation of Default ValueEager: The default value is eagerly evaluated regardless of whether the Optional contains a value or not.Lazy: The supplier function is lazily evaluated and invoked only when the Optional is empty.
UsageWhen the default value is a simple constant.When default value needs to be computed.
Performance ImpactUnnecessary computation can harm the performance when the Optional is not empty.No impact on performance.

1. The Difference between orElse() and orEleseGet() Methods

Though both methods, orElse() and orEleseGet(), return a default specified value when the optional is empty. Still, they have some big differences which we must know before using these methods.

1.1. Method Parameters

  • The orElse() method takes a precomputed value or a function call that will return the default value.
  • The orEleseGet() method takes a supplier function (a Supplier instance) to generate the default value lazily.
orElse(T other)
orElseGet(Supplier<? extends T> otherSupplier)

1.2. Evaluation of Default Value

The default value provided to orElse() is eagerly evaluated. It means that the default value is evaluated regardless of whether the Optional contains a value or not.

In the following example, we get the “Generating Default Value” printed in the console. It means that the function was executed even though the Optional was not empty.

Optional<String> optionalValue = Optional.of("Hello");
String result = optionalValue.orElse( generateDefaultValue() );	// Using orElse()
System.out.println(STR."Result using orElse(): \{result}");

public static String generateDefaultValue() {
	System.out.println("Generating Default Value");
	return "Default Value";
}

Program output:

Generating Default Value
Result using orElse(): Hello

The supplier function provided to orElseGet() is lazily evaluated. It means that the supplier function is invoked only when the Optional is empty, thus avoiding unnecessary computation if the value is present.

In the following example, the supplier function is NOT evaluated. It will be invoked only when the Optional is empty.

Optional<String> optionalValue = Optional.of("Hello");
String result = optionalValue.orElseGet(() -> generateDefaultValue() );  // Using orElseGet()
System.out.println(STR."Result using orElseGet(): \{result}");

public static String generateDefaultValue() {
	System.out.println("Generating Default Value");
	return "Default Value";
}

Program output:

Result using orElseGet(): Hello

2. Performance Impact

Quite obviously, when using the orElse() method, since the default value is eagerly evaluated, this will lead to unnecessary computation even when the value is present. Even though the method to compute the default value is inexpensive, it is still a waste of resources. And if the function is expensive then it can lead to significant performance impact.

The lazy evaluation of the supplier function in orElseGet() avoids unnecessary computation when the value is present. This surely helps in preventing resource misuse.

3. When to use orElse() or orElseGet()?

Based on the above discussion, we can safely conclude that when the default value is a simple constant and does not require computation, we should use orElse() method.

In contrast, when we are required to execute a method or statements for computing the default value, we should always go for orElseGet() method. This will save system resources when the optional is not empty.

4. Conclusion

This is very important to understand the basic difference between both methods, orElse() and orEleseGet(), to use them efficiently and save some computation cycles. Using orElse() with methods, that are resources heavy, can bring down the performance of the application.

Happy Learning !!

Source Code on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode