问题
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