If else code execution with Optional class
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
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"));
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));