Multiple null checks using Optional in Java 8

Pi53 :

I want to simplify the below piece of code with multiple if and else statements using Java 8. Is there a way to get rid of them altogether using some Java 8 feature, e.g. Optional? I tried to find something here but couldn't find an answer.

LocalDateTime beDate = someDate;
LocalDateTime aeDate = someDate;
LocalDateTime eDate;

if (beDate == null && aeDate == null) {
    eDate = null;
}
else if (beDate != null && aeDate == null) {
    eDate = beDate;
}
else if (beDate == null && aeDate != null) {
    eDate =  aeDate;
}
else if (beDate != null && aeDate != null && 
        (beDate.isEqual(aeDate) || beDate.isBefore(aeDate))) {
    eDate = beDate;
}
else {
    eDate = aeDate;
}
chrylis -on strike- :

The logic here is very difficult to understand. Instead, express your intention more directly:

private static final Comparator<ChronoLocalDateTime<?>> EARLIEST_PRESENT = 
    Comparator.nullsLast(Comparator.naturalOrder());

LocalDateTime eDate = BinaryOperator.minBy(EARLIEST_PRESENT).apply(beDate, aeDate);

(Note that static imports for the elements from Comparator and BinaryOperator will make this even clearer.)

Guess you like

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