Understanding Optional.orElse() vs Optional.orElseGet()


In Java, Optional provides a way to handle potentially null values safely. The methods orElse() and orElseGet() are used to provide default values when an Optional is empty. However, the difference between these two methods is important depending on the cost of the default value computation.

Step 1: Define the Default Method

Let's assume we have a method that returns a default value of type String:


public String getDefault() {
System.out.println("Getting Default Value");
return "Default Value";
}

Step 2: Examine the Two Cases

Case 1: Using orElseGet()

String name = Optional.of(value)
.orElseGet(() -> getDefault());

  • Here, getDefault() is called only if value is null. This means getDefault() is evaluated lazily (only when needed).

Case 2: Using orElse()

String name = Optional.of(value)
.orElse(getDefault());
  • In this case, getDefault() is called always, regardless of whether value is null or not. This means getDefault() is eagerly evaluated.

Key Difference:

  • In Case 1, getDefault() will be executed only if the Optional is empty (i.e., value is null).
  • In Case 2, getDefault() will be executed every time, even if the Optional is not empty.

Conclusion:

  • If getDefault() is not expensive to compute (i.e., it doesn't take a long time), either orElse() or orElseGet() can be used since the result will be the same.
  • However, if getDefault() is expensive to compute (e.g., involves time-consuming operations), you should prefer Case 1 (using orElseGet()), as it ensures getDefault() is only called when necessary.

Message for Readers: Keep learning a little every day, and don't forget to take notes to solidify your understanding!

#Java #Optional #LazyEvaluation

Comments

Popular posts from this blog

Fixing the DeepSpeed Import Error While Fine-Tuning the Qwen Model

Amazon Linux 2023 - User data configuration for launch templates to connect to the EKS cluster

How to create ISM policy and rotate logs in opensearch