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

Optional that test if a value is not null AND not empty

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

我们该怎么做?

鉴于:

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