java 8 Optional code example
Example 1: check if optional is empty java
@Test
public void givenNull_whenCreatesNullable_thenCorrect() {
String name = null;
Optional<String> opt = Optional.ofNullable(name);
assertFalse(opt.isPresent());
}
Example 2: instantiate optinal java 8
Person p = new Person();
Optional<Person> op = Optional.of(p);
Example 3: java optional to collection
public static <T> List<T> toList(Optional<T> opt) {
return opt
.map(Collections::singletonList)
.orElseGet(Collections::emptyList);
}