At the time of writing this article, I don't know much about the grammar of java.util.Optional.
Class added in Java8-java.util.Optional
** A container object that may or may not contain non-null values. ** ** by https://docs.oracle.com/javase/jp/8/docs/api/java/util/Optional.html
I see, I don't know.
orElse(T other) Returns a value if it exists, otherwise it returns another.
orElseGet(Supplier<? extends T> other) Returns the value if it exists, calls other otherwise, and returns the result of that call.
Main.java
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Optional.of("hoge").orElseGet(() -> {
System.out.println("It's not executed or ElseGet");
return "";
});
Optional.empty().orElseGet(() -> {
System.out.println("It's orElseGet to be executed");
return "";
});
String piyo = (String)Optional.of("hoge").orElse("It's not returned or Else");
System.out.println("piyo: " + piyo);
String piyo2 = (String)Optional.empty().orElse("It's returned or Else");
System.out.println("piyo2: " + piyo2);
}
}
It's orElseGet to be executed piyo: hoge piyo2: It's returned or Else
orElse () is executed regardless of whether the contents of Optional are null, and oeElseGet () is executed only when null.
--OrElse () is good because it is useless to write a lambda expression just to return a constant like "returns an empty string or zero if null" --OrElseGet () in the case of "If it is null, do some processing and return the result"
Recommended Posts