java - 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```
有没有办法做到这一点?
解决方案
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"));
推荐阅读
- php - 如何通过 curl 库从请求中发送所有文件
- javascript - 究竟是什么关于 reduce 并且无法在 Javascript 中突破它?
- sql - 使用 sql 查询获取总折扣
- nginx - 如何从内部网络关闭 IP 的 gzip 内容编码?
- powershell - 如何确保powershell中的字体在winPE下相同?
- go - 类型将自定义类型断言为基本类型
- javascript - 试图以随机顺序显示 JavaScript 测验的问题
- mysql - 如何编写 SQL 命令以使用同一表中另一列的数据输入一列?
- r - 我怎样才能问一个很棒的 ggplot / lattice / base plot 问题?
- windows - 将带有一个单引号的参数传递给 .PS1 脚本