Rewriting Optional without using isPresent

xiwuroke :
void spendTheNight() {
    Optional<Homework> homework = getHomeworkDueTonight();
    if (homework.isPresent()) {
        rushThrough(homework.get());
    } else {
        homework = getHomeworkDueNextWeek();
        if (homework.isPresent()) {
            workSlowlyOn(homework.get());
        } else {
            partyHard();
        }
    }
    goToBed();
}

I know it's bad practice to do if..else with isPresent; how can I rewrite this to make better use of Optional such that the flow of logic stays the same?

I was thinking of using or, orElse, or orElseGet, but not sure how to use them here, with that additional assignment in the first else.

(assume the custom methods can't be modified and must be used as-is)

Naman :

All the listed APIs by you or, orElse, or orElseGet return one or the other value, your code seems to be more around running a stub based on some conditions around return types of the methods.

You can use ifPresentOrElse in such a case, since Java 9:

Optional<Homework> homework = getHomeworkDueTonight(); 
homework.ifPresentOrElse(this::rushThrough, () -> { 
    Optional<Homework> hw = getHomeworkDueNextWeek(); 
    hw.ifPresentOrElse(this::workSlowlyOn, this::partyHard); 
});
goToBed();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=296069&siteId=1