If else code execution with Optional class

Mani :

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?

Naman :

Java-9

Java-9 introduced ifPresentOrElse for something similar in implementation. You could use it as :

Optional.ofNullable(words[5])
        .map(String::toLowerCase) // mapped here itself
        .ifPresentOrElse(System.out::println,
                () -> System.out.println("word is null"));

Java-8

With Java-8, you shall include an intermediate Optional/String and use as :

Optional<String> optional = Optional.ofNullable(words[5])
                                    .map(String::toLowerCase);
System.out.println(optional.isPresent() ? optional.get() : "word is null");

which can also be written as :

String value = Optional.ofNullable(words[5])
                       .map(String::toLowerCase)
                       .orElse("word is null");
System.out.println(value);

or if you don't want to store the value in a variable at all, use:

System.out.println(Optional.ofNullable(words[5])
                           .map(String::toLowerCase)
                           .orElse("word is null"));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=37123&siteId=1