26 March 2010

Filtering nulls from an array

Valid since: op4j 1.0

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

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.

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

Integer[] filteredValues =

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) {
Integer[] filteredValues = 
    filteredValuesList.toArray(new Integer[filteredValuesList.size()]);

No comments:

Post a Comment