Sobes.tech
Junior — Middle

Mis vahe on Java meetoditel orElse ja orElseGet ning millised on nende kasutamise omadused?

sobes.tech AI

Vastus AI-lt

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

  • orElse(T other) — accepts a default value that is calculated immediately upon method call, regardless of whether there is a value in the Optional.
  • orElseGet(Supplier<? extends T> other) — accepts a supplier (function) that is called only if the value is missing, meaning the value calculation is deferred until needed.

Usage features:

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

Example:

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

// orElse always calculates "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("Calculating default value");
    return "default";
}