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:


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:

  • StringUtils.isEmpty(String) / StringUtils.isNotEmpty(String): It tests if the String is null or empty (" " is not empty)
  • StringUtils.isBlank(String) / StringUtils.isNotBlank(String): Same as isEmpty bt if the String is only whitespace it is considered blank

And applied to Optional you get:

Optional.ofNullable(myString).filter(StringUtils::isNotEmpty).orElse("value was null or empty");
©2020 Emmanuel Balpe. All Rights Reserved. Built with NextJS.