Java 8 可选 : choose between two possibly null values

标签 java java-8 option-type

我必须在两个字符串变量之间做出选择 - 第一个具有非 null 值。 如果它们都是 null - 那么我想退出该方法。 这可以在以下代码中完成:

String value1 = <get from somewhere>
String value2 = <get from somewhere else>
String target = null;
if (value1 != null) target = value1;
else if (value2 != null) target = value2;
if (target == null) return null;

也可以简写:

String target = value1 != null ? value1 : value2 != null ? value2 : null;
if (target == null) return null;

我正在努力解决如何使用 Optional
以流畅的形式执行此操作 注意:我只能使用 Java 8 语法(所以没有 Optional.or())

最佳答案

String target = Optional.ofNullable(value1).orElse(value2)

如果 value1 == null,则返回 value2 - 要么有值要么为 null。无需通过将 value2 == null 映射到 null 来显式处理这种情况。

关于Java 8 可选 : choose between two possibly null values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52756892/

相关文章:

java - TeeChart:将蜡烛添加到图表中而不指定其时间

ios - 如何在 Switch 语句中使用可选整数

java - OnActivityResult 中启动 Activity 给出空指针

java - 无法使用 Gradle 构建 Android 应用程序

java - JDK 库是否提供 lambda 'invoker' 实用程序类?

java - 使用 Java 8 Lambda 表达式查找票据列表是否具有不同货币

java - 如何使用 Java Optional 优雅地替换三元运算符

xcode - fatal error : unexpectedly found nil while unwrapping an Optional value (lldb)

java - 使用 Spring 与 jar 相关的文件

spring - Reactor Mono 与 CompletableFuture