Optional study sample
/**
*Optional study
* @author komikcomik
*
*/
public class OptionalHello {
public static void main(String[] args) {
String null= null;
String is not null= "abc";
if (Optional.ofNullable(null).equals(Optional.empty())) {
System.out.println("Was null");
} else {
System.out.println("It wasn't null");
}
if (Optional.ofNullable(It's not null).equals(Optional.empty())) {
System.out.println("It was null 2");
} else {
System.out.println("It wasn't null 2");
}
Optional.ofNullable(null).ifPresent(s -> System.out.println(s));
Optional.ofNullable(It's not null).ifPresent(s -> System.out.println(s));
}
}
Execution result
Was null
It wasn't null 2
abc
The example is not cool this time, but it seems that it is actually good to use Optional for the return value of the method.
Recommended Posts