zeroIfNull() is a DurationUtils that returns the passed Duration object if it is non-null. Otherwise, it returns Duration.ZERO.
Duration.ZERO?Duration.ZERO is a Duration object with zero seconds and zero nanoseconds.
DurationUtilsThe definition of DurationUtils can be found in the Apache Commons Lang package, which we can add to the Maven project by adding the following dependency to the pom.xml file:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
For other versions of the commons-lang package, refer to the Maven Repository.
You can import the DurationUtils class as follows:
import org.apache.commons.lang3.time.DurationUtils;
public static Duration zeroIfNull(final Duration duration)
final Duration duration: The duration object to check.This method returns the given duration object if the object is non-null. Otherwise, it returns Duration.ZERO.
import org.apache.commons.lang3.time.DurationUtils;import java.time.Duration;public class Main{public static void main(String[] args) {// Example 1Duration duration = Duration.ofDays(3);System.out.printf("DurationUtils.zeroIfNull(%s) = %s", duration, DurationUtils.zeroIfNull(duration));System.out.println();// Example 2duration = null;System.out.printf("DurationUtils.zeroIfNull(%s) = %s", duration, DurationUtils.zeroIfNull(duration));}}
Duration = PT72HThe method returns PT72H, i.e., the passed object because the passed Duration object is non-null.
Duration = nullThe method returns PT0S because the passed Duration object is null.
The output of the code will be as follows:
DurationUtils.zeroIfNull(PT72H) = PT72H
DurationUtils.zeroIfNull(null) = PT0S