Depends on what you mean by "cleaner."
An ifPresent
solution, as @Naman points out, looks like:
firstRequiredOptional.ifPresent(firstValue ->
secondRequiredOptional.ifPresent(secondValue -> {
// do something with firstValue, secondValue.
}));
This is "cleaner" in the sense that you don't have to call both .isPresent()
and .get()
on the two optionals.
There's no Optional<FirstType, SecondType>
, but if the combination of these two required values has some kind of meaning, you might want to embody this in a class.
Optional<FullName> fullNameOptional = firstNameOptional.flatMap(firstName ->
secondNameOptional.map(secondName -> new FullName(firstName, secondName));
fullNameOptional.ifPresent(fullName -> {
// do something with fullName.
});
This has the advantage of giving you a single Optional value you can work with, passing to helper methods, etc., and it follows the Command-Query Separation pattern, which tends to have advantages when debugging and breaking your code down into pieces that are simple to unit-test. But it's not "cleaner" in the sense that you're using less code, for example.
If you like the idea of mapping to a single Optional
, but don't want to create a type just for this purpose, you can create general-purpose Tuple classes (or use one of several popular Tuple libraries).