27 March 2010

Converting an array of Strings into a null-free array of Integers

Valid since: op4j 1.0

Description
Convert an array of String objects representing valid integer numbers into an array of Integer objects, having filtered all null values out of the array.

Scenario
We have a String[] like:
// strArray == ARRAY [ "431", null, "94", "398" ]
And we want to convert it into an Integer[] containing no null elements.

Recipe
Two actions will be needed:
  • First, execute the conversion from String to Integer.
  • Second, remove all nulls from the resulting array.
Integer[] values =
    Op.on(strArray).map(Types.INTEGER, FnString.toInteger()).removeAllNull().get();


Comments
Note that because arrays are not collections, and instantiating them requires creating an instance of a specific class (instead of a generic class like java.util.List or java.util.Set), executing a function that changes the type of the elements of an array requires specifying the new type, which is done with that Types.INTEGER parameter seen above. This is an org.javaruntype.type.Type object, from the javaRuntype library.

Mapping (executed here via a map(...) action) is equivalent to iterating, executing a function, and then ending the iteration. So, the code above is equivalent to:
Integer[] values =
    Op.on(strArray).
        forEach().exec(Types.INTEGER, FnString.toInteger()).endFor().
        removeAllNull().get();

Let's see the equivalent non-op4j Java code:
List valuesList = new ArrayList();
for (String element : strArray) {
    if (element != null) {
        valuesList.add(Integer.parseInt(element));
    }
}
Integer[] values = valuesList.toArray(new Integer[valuesList.size()]);

No comments:

Post a Comment