代码之家  ›  专栏  ›  技术社区  ›  Joshua Goldberg

一种返回可选值(如果存在)而不保存或派生两次的方法?

  •  2
  • Joshua Goldberg  · 技术社区  · 9 年前

    我想做如下事情,其中 x 将被退回 从包含函数 如果存在可选选项,则“继续处理”:

    stuff().that().returns().optional().ifPresent(x -> return x);
    // otherwise continue processing
    ...
    return alternateResult;
    

    这样的东西也可以:

    if (stuff().that().returns().optional().isPresent()) {
        return thatResult;
    }
    // otherwise continue processing
    ...
    return alternateResult;
    

    但这样的想法行不通: return 在lambda中,只是从lambda返回,在第二种情况下,在检查之后,我没有返回闭包中的值 isPresent() 有没有更简洁的习语我可以用?

    2 回复  |  直到 9 年前
        1
  •  4
  •   Alex - GlassEditor.com    9 年前

    如果您可以在lambda中完成其余的处理,则可以使用 orElseGet :

    return stuff().that().returns().optional().orElseGet(() -> {
        ...
        return alternateResult;
    });
    
        2
  •  1
  •   Joshua Goldberg    9 年前

    到目前为止我想出的最好的。这是最好的吗?

    Optional<ExplicitType> maybeResult = stuff().that().returns().optional();
    if (maybeResult.isPresent()) {
        return maybeResult.get();
    }
    // otherwise continue processing
    ...
    return alternateResult;