Share the joy
Optional can avoid null of an Object.
public static void nullable() { Optional<Integer> i = Optional.fromNullable(null); System.out.println(i.or(2)); // output 2, because is null System.out.println(i.get()); // IllegalStateException } public static void absent() { Optional<Integer> i = Optional.absent(); System.out.println(i.or(2)); // output 2, because value is absent System.out.println(i.get()); // IllegalStateException } public static void of() { Optional<Integer> i = Optional.of(1); System.out.println(i.get()); // output 1 System.out.println(i.or(2)); // return 1, because it has value }
Best use case is that when we initialize the value, we use Optional.fromNullable(). When we get the value, we use Optional.or(), Optional.orNull().
Reference: https://www.tutorialspoint.com/guava/guava_optional_class.htm