26 March 2010

Filtering nulls from an array

Valid since: op4j 1.0

Description
Given an array (or list, or set), remove all its null elements.

Scenario
We have an Integer[] variable called values, like:
// values == ARRAY [ null, 12, 43, 92, null, 34 ]
...and we want to easily remove all null elements from it.

Recipe
Just execute the removeAllNulls() action on the array and return the result:

Integer[] filteredValues =
    Op.on(values).removeAllNull().get();


Comments
There are many remove methods, like for example removeAllTrue(function), which determines whether an element has to be removed or not depending on the result of executing a function passed as a parameter.

Equivalent non-op4j Java code:
List<Integer> filteredValuesList = new ArrayList<Integer>();
for (Integer value : values) {
    if (value != null) {
        filteredValuesList.add(value);
    }
}
Integer[] filteredValues = 
    filteredValuesList.toArray(new Integer[filteredValuesList.size()]);

No comments:

Post a Comment