How to chain Optional#ifPresent() in lambda without nesting?

爱⌒轻易说出口 提交于 2019-12-12 14:42:59

问题


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().

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

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();
}

回答1:


You can use flatMap:

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

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.




回答2:


perhaps (or am i missing what you don't like about gets?)

static Optional<String> getA() {
    return Optional.of("a");
}

static Optional<String> getB(String b) {
    return Optional.of(b + "!");
}

static void test() {
    Optional<String> a, b;
    a = getA();
    if (a.isPresent() && (b = getB(a.get())).isPresent()) {
        System.out.println(b.get());
    }
}


来源:https://stackoverflow.com/questions/46802131/how-to-chain-optionalifpresent-in-lambda-without-nesting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!