可选,测试值是否不为空且不为空

fla*_*ant 0 java java-8 option-type

我想对以下结果使用可选:如果值(字符串)为 null 或为空,则返回“TOTO”,否则返回该值。

我们应该怎么做 ?

Ben*_*n M 6

鉴于:

\n
String s = null;\n
Run Code Online (Sandbox Code Playgroud)\n

简单的方法没有Optional

\n
if(s == null ||\xc2\xa0s.isEmpty()) {\n  return "TOTO";\n}\n
Run Code Online (Sandbox Code Playgroud)\n

包裹着Optional

\n
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\n
Run Code Online (Sandbox Code Playgroud)\n