【发布时间】:2021-03-10 16:35:43
【问题描述】:
我想为以下结果使用可选值:如果值(字符串)为 null 或为空,则返回“TOTO”,否则返回该值。
我们怎样才能做到这一点?
【问题讨论】:
我想为以下结果使用可选值:如果值(字符串)为 null 或为空,则返回“TOTO”,否则返回该值。
我们怎样才能做到这一点?
【问题讨论】:
给定:
String s = null;
没有Optional的简单方法:
if(s == null || s.isEmpty()) {
return "TOTO";
}
用Optional包装:
String result = Optional.ofNullable(s) // will filter the value if it is null
.filter(str -> !str.isEmpty()) // will filter the value if it is empty
.orElse("TOTO"); // default value if Optional is empty
【讨论】:
null,则示例代码返回"TOTO"
return ( s == null || s.isEmpty() ) ? "TOTO" : s;