orElseは、isEmpty() = trueの場合に別の値にすり替える
orElseGet()はSupplier
orElseThrow()は extends Throw> Supplier
class SampleException extends Exception {
}
public class Outer {
public static void main(String[] args) {
System.out.println(Optional.<String>of("A").orElse("X"));
System.out.println(Optional.<String>empty().orElse("X"));
System.out.println(Optional.<String>empty().orElseGet(() -> "Y"));
try {
System.out.println(Optional.<String>empty().orElseThrow(() -> new SampleException()));
} catch (SampleException ex) {
ex.printStackTrace();
}
}
}
A
X
Y
com.mycompany.mavenproject1.SampleException
at com.mycompany.mavenproject1.Outer.lambda$main$1(Outer.java:18)
at java.base/java.util.Optional.orElseThrow(Optional.java:408)
at com.mycompany.mavenproject1.Outer.main(Outer.java:18)