首页 > 解决方案 > If else 使用 Optional 类执行代码

问题描述

我正在阅读可选课程的教程 - https://www.geeksforgeeks.org/java-8-optional-class/它具有以下内容

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

我正在尝试使用as的ifPresent检查来减少行数Optional

Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase()))

但无法进一步获得其他部分

Optional.ofNullable(words[5]).ifPresent(a -> System.out.println(a.toLowerCase())).orElse();// doesn't work```

有没有办法做到这一点?

标签: javajava-8optional

解决方案


Java-9

Java-9 是ifPresentOrElse为了实现类似的东西而引入的。您可以将其用作:

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

Java-8

使用 Java-8,您应该包含一个中间Optional/String并用作:

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

也可以写成:

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

或者,如果您根本不想将值存储在变量中,请使用:

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

推荐阅读