在 Java 8 中展开多个可选变量
我有以下问题。假设您有 2 个变量Optional
Optional<Contact> c1 = ...
Optional<Contact> c2 = ...
和一个需要 2 个联系人类型的变量的方法
void match(Contact c1, Contact c2) {...}
你需要解开c1和c2 vars的包装,并将它们传递到方法中。Optional
match()
我的问题是“在Java 8中,哪种方式最优雅?
到目前为止,我已经找到了2种方法:
-
通过使用 isPresent
if (c1.isPresent() && c2.isPresent()) { match(c1.get(), c2.get()); }
-
通过使用嵌套 ifPresent
c1.ifPresent((Contact _c1) -> { c2.ifPresent((Contact _c2) -> { match(_c1, _c2); }); });
在我看来,这两种方式都很糟糕。在Scala中,我可以这样做:
for {
contact1 <- c1
contact2 <- c2
} yield {
match(contact1, contact2);
}
在Java 8中,有没有办法比我上面概述的更整洁?