Sobes.tech
Junior — Middle

What is the difference between the orElse and orElseGet methods in Java, and what are their usage features?

sobes.tech AI

Answer from AI

In Java, the methods orElse and orElseGet are used with the Optional class to specify a default value if the object is absent.

  • orElse(T other) — takes a default value that is computed immediately when the method is called, regardless of whether the Optional contains a value.
  • orElseGet(Supplier<? extends T> other) — takes a supplier (function) that is called only if the value is absent, meaning the computation of the value is deferred until necessary.

Usage features:

  • If computing the default value is expensive or has side effects, it is better to use orElseGet to avoid unnecessary costs.
  • If the value is simple and quick to compute, you can use orElse.

Example:

Optional<String> opt = Optional.empty();

// orElse always computes "default"
String result1 = opt.orElse(getDefault());

// orElseGet calls getDefault() only if opt is empty
String result2 = opt.orElseGet(() -> getDefault());

public String getDefault() {
    System.out.println("Computing default value");
    return "default";
}
What is the difference between the orElse and… - sobes.tech