If else code execution with Optional class

人走茶凉 提交于 2020-06-25 09:16:28

问题


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?


回答1:


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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/54068505/if-else-code-execution-with-optional-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!