I have the following problem. Let's say you have 2 Optional
variables
Optional<Contact> c1 = ...
Optional<Contact> c2 = ...
and a method which needs 2 variables of type Contact
void match(Contact c1, Contact c2) {...}
and you need to unwrap both c1 and c2 Optional
vars and pass them into the match()
method.
My question is "Which is the most elegant way to do that in Java 8?"
So far I've found 2 ways:
by using isPresent
if (c1.isPresent() && c2.isPresent()) { match(c1.get(), c2.get()); }
by using nested ifPresent
c1.ifPresent((Contact _c1) -> { c2.ifPresent((Contact _c2) -> { match(_c1, _c2); }); });
Both ways are terrible in my opinion. In Scala I can do this:
for {
contact1 <- c1
contact2 <- c2
} yield {
match(contact1, contact2);
}
is there a way in Java 8 to do it neater than I outlined above?