Java Optionals

Replace if != null statement with a Java optional

if(myVar != null){
    logger.info("MyVar=" + myVar);
}
Optional.ofNullable(myVar).ifPresent(var -> logger.info("MyVar=" + var));

So we all have a lot of terner expression like that in our codebases:

contrat.getDate() != null ? contrat.getDate().toString() : "";

You can now simplify this with:

Optional.ofNullable(contrat.getDate()).map(LocalDate::toString).orElse("");

String null or empty

Optional.ofNullable(myString).orElse("value was null");
Optional.ofNullable(myString).ifPresent(s -> System.out.println(s));
Optional.ofNullable(myString).orElseThrow(() -> new RuntimeException("value was null"));

And to test if it is null or empty you can use Apache org.apache.commons.lang3 library that gives you the following methods:

And applied to Optional you get:

Optional.ofNullable(myString).filter(StringUtils::isNotEmpty).orElse("value was null or empty");
← Back to home