则使用Optional类执行代码

则使用Optional类执行代码

本文介绍了如果是,则使用Optional类执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里浏览了Optional类的教程- https://www .geeksforgeeks.org/java-8-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");
}

我正在尝试使用OptionalifPresent检查来使行数减少

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

但无法进一步了解else部分

but not able to get the else part further

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

有办法吗?

推荐答案

Java-9

Java-9引入了 ifPresentOrElse 中的实现类似.您可以将其用作:

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

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

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

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

这篇关于如果是,则使用Optional类执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:20