I was going through a tutorial of Optional class here - https://www.geeksforgeeks.org/java-8-optional-class/ which has the following
String[] words = new String[10];
Optional<String> checkNull = Optional.ofNullable(words[5]);
if (checkNull.isPresent()) {
String word = words[5].toLowerCase();
System.out.print(word);
} else{
System.out.println("word is null");
}
I am trying to make it of less lines using ifPresent check of Optional as
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase()))
but not able to get the else part further
Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase())).orElse();// doesn't work```
Is there a way to do it?
System.out.println(Optional.ofNullable(words[5]).map(String::toLowerCase).orElse("Not Present"));