I have a class that can contain multiple optional IDs, the class will pick the first available and return it to the caller. Something like the below.
Optional<Phone> homePhone;
Optional<Phone> mobilePhone;
Optional<Phone> emergencyPhone;
Phone getBestPhone() {
return homePhone.map(p -> p)
.orElse(mobilePhone.map(p -> p)
.orElse(emergencyPhone.map(p -> p)
.orElseThrow(() -> new IllegalArgument("No valid phone")))));
}
I'd like to use the optional methods like map and orElse but in this case it leads to way too much nesting. Two other pseudocode options might be.
Phone getBestPhone() {
homePhone.ifPresent(p -> { return p; });
mobilePhone.ifPresent(p -> { return p; });
emergencyPhone.ifPresent(p -> { return p; });
throw new IllegalArgument("...");
}
Phone getBestPhone() {
return FirstPresent(homePhone, mobilePhone, emergencyPhone);
}
Are there any better ways that the existing method I have? I'm very tempted to avoid the nesting by doing vanilla isPresent() checks.