mercredi 18 mars 2020

Multiple null checks using Optional in Java 8

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

LocalDateTime beDate= someDate;
LocalDateTime aeDate = someDate;
LocalDateTime eDate = null;
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;
}

Aucun commentaire:

Enregistrer un commentaire