如何在不嵌套的情况下在lambda中链接Optional#ifPresent()? [英] How to chain Optional#ifPresent() in lambda without nesting?

查看:317
本文介绍了如何在不嵌套的情况下在lambda中链接Optional#ifPresent()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码块,要求我检查是否存在多个嵌套变量.这些最初是我用OptionalifPresent()代替的空检查.

I have the following code block that requires that I check whether multiple nested variables are present. These were originally null checks that I replaced with Optional and ifPresent().

我想使用ifPresent()而不是查询get()来减轻潜在的运行时异常.但这会导致很多嵌套.

I would like to use ifPresent() instead of querying get() to mitigate potential runtime exceptions. But this is causing a lot of nesting.

在此示例中,我可以利用lambda来实现相同的流程而无需嵌套吗?

Can I leverage lambdas in this example to achieve the same flow without the nesting?

void SomeMethod() {
    procA().ifPresent(a -> {
       procB(a).ifPresent(b -> {
          // Do something

          return;
       });
    });

    throw new SomeException();
}

推荐答案

您可以使用

You can use flatMap:

procA().flatMap(this::procB).ifPresent(b -> {
    // do something
});

对于return语句,您不能从lambda内部的外部方法返回.如果要在缺少该值时引发自定义异常,请使用

As for the return statement, you can't return from the outer method inside the lambda. If you want to throw a custom exception when the value is missing, use orElseThrow:

B b = procA()
        .flatMap(this::procB)
        .orElseThrow(SomeException::new);

// do something with b

或者,当然,您可以只调用

Or, of course you could just call get and let it throw a NoSuchElementException.

这篇关于如何在不嵌套的情况下在lambda中链接Optional#ifPresent()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆