I have the following problem. Let's say you have 2 Optional variables
Optional<Contact> c1 = ... Optional<Contact> c2 = ...
and a method that requires 2 variables of type Contact
void match(Contact c1, Contact c2) {...}
and you need to deploy both c1 and c2 Optional vars and pass them to the match() method.
My question is "What is the most elegant way to do this in Java 8?"
So far I have found 2 ways:
using isPresent
if (c1.isPresent() && c2.isPresent()) { match(c1.get(), c2.get()); }
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 make this tidier than the above?
java scala optional
Nico
source share