IterableUtils – Example

In this post, we are going to see how we can use IterableUtils of Apache commons collections with an example.

Assume that you want to retrieve a key value from environmental variables. If its not available, then we would need to get it from system properties. If its not available even there, then we would need to assume a default value.

We can easily do it with an if else. But with the use of IterableUtils, we can avoid those boiler plate code.

Refer the below code.

import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.functors.NotNullPredicate;

import java.util.Arrays;

public class IterableMain {

    public static void main(String[] args) {
        //Get the default value
        System.out.println("Uses default app name:" + getKeyValue("APP_NAME", "Default App Name"));
        //Get the key value from system properties
        System.setProperty("APP_NAME", "App Name1");
        System.out.println("Uses system property app name:" + getKeyValue("APP_NAME", "Default App Name"));

    private static String getKeyValue(String key, String defaultValue) {
        String envKey = System.getenv(key);
        String propKey = System.getProperty(key);
        return IterableUtils.find(Arrays.asList(envKey, propKey, defaultValue), NotNullPredicate.notNullPredicate());


In the above code, we first retrieve the key value from environmental variables and also from system properties and create a list contains the envKeyValue, propKeyValue and also a default value. We have to keep the order as is.

Then we use IterableUtils and invoke find method and pass that list and the Not Null predicate. Hence the first not null value would be returned as an output.

** If the key presents in environmental variable then environment value would be returned.

** If the key is not there in environmental variable but present in system properties, then the list looks like this (null, “App Name1”, “Default App Name”). So the first not null value would be returned as an output. So “App Name1” is the output.

** If none of the values exist, then the list looks like this (null, null, “Default App Name”). So the default app name would be returned.

The output of the above program is given below,

Uses default app name:Default App Name
Uses system property app name:App Name1