fla*_*ant 0 java java-8 option-type
我想对以下结果使用可选:如果值(字符串)为 null 或为空,则返回“TOTO”,否则返回该值。
我们应该怎么做 ?
鉴于:
\nString s = null;\nRun Code Online (Sandbox Code Playgroud)\n简单的方法没有Optional:
if(s == null ||\xc2\xa0s.isEmpty()) {\n return "TOTO";\n}\nRun Code Online (Sandbox Code Playgroud)\n包裹着Optional:
String result = Optional.ofNullable(s) // will filter the value if it is null\n .filter(str -> !str.isEmpty()) // will filter the value if it is empty\n .orElse("TOTO"); // default value if Optional is empty\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
2235 次 |
| 最近记录: |