0
0

More than 1 year has passed since last update.

orElse, orElseGet, orElseThrow of Optional class

Last updated at Posted at 2023-01-25

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)
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0