use Optional as a return type but never als a method - argument;
Optional<String> opt = Optional.of("baeldung");
opt.ifPresent(name -> System.out.println(name.length()));
String nullName = null;
String name = Optional.ofNullable(nullName).orElseGet(() -> "john");
assertEquals("john", name);
String result = Optional.ofNullable(text).orElseGet(this::getMyDefault);
String nullName = null;
// throws a NoSuchElementException
String name = Optional.ofNullable(nullName).orElseThrow();
Optional.ofNullable(modem2)
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent(price->doSomeThing(price));
List<String> companyNames = Arrays.asList(
"paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
int size = listOptional
.map(List::size)
.orElse(0);
// returns empty Optional
Optional<Guitarist> lookupResult = guitaristService.findByLastName("Page");
lookupResult.ifPresentOrElse(
guitarist -> System.out.println(guitarist.getSignatureSong()),
() -> System.out.println("Guitarist not found!")
);