【问题标题】:Optional that test if a value is not null AND not empty [duplicate]可选,测试值是否不为空且不为空 [重复]
【发布时间】:2021-03-10 16:35:43
【问题描述】:

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

我们怎样才能做到这一点?

【问题讨论】:

    标签: java java-8 optional


    【解决方案1】:

    给定:

    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
    

    【讨论】:

    • 感谢您的回答。是的,我想用 Optional 来做,但是当 str 为空时,它不起作用
    • 什么不起作用?如果提供的字符串是null,则示例代码返回"TOTO"
    • 对不起,它有效,我很抱歉
    • 或者只是return ( s == null || s.isEmpty() ) ? "TOTO" : s;
    猜你喜欢
    • 1970-01-01
    • 2018-02-16
    • 2011-04-05
    • 2016-05-04
    • 2012-10-29
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多