Mani
Mani

Reputation: 1208

If else code execution with Optional class

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?

Upvotes: 9

Views: 5951

Answers (3)

Ryuzaki L
Ryuzaki L

Reputation: 40048

For a bit to be more clear ifPresent will take Consumer as argument and return type is void, so you cannot perform any nested actions on this

public void ifPresent(Consumer<? super T> consumer)

If a value is present, invoke the specified consumer with the value, otherwise do nothing.

Parameters:

consumer - block to be executed if a value is present

Throws:

NullPointerException - if value is present and consumer is null

So instead of ifPreset() use map()

String result =Optional.ofNullable(words[5]).map(String::toLowerCase).orElse(null);

print Just to print

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

Upvotes: 4

Naman
Naman

Reputation: 31878

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"));

Upvotes: 12

Vishwa Ratna
Vishwa Ratna

Reputation: 6390

If you are using java 9, you can use ifPresentOrElse() method::

https://docs.oracle.com/javase/9/docs/api/java/util/Optional.html#ifPresentOrElse-java.util.function.Consumer-java.lang.Runnable-

Optional.of(words[5]).ifPresentOrElse(
   value -> System.out.println(a.toLowerCase()),
   () -> System.out.println(null)
);

If Java 8 then look this great cheat sheet :

http://www.nurkiewicz.com/2013/08/optional-in-java-8-cheat-sheet.html

Upvotes: 3

Related Questions