Mapping data in collections

Use the map method to create an array list from a collection. A block expression transforms each element in the collection and stores the result as element in the new array list. For example, the following Gosu code declares and initializes an ArrayList of String objects. Then, it maps the lengths of the strings to a new array list.

// Declare and initialize an array list of strings. 
var myStrings = new ArrayList<String>(){"a", "b", "bb", "ab", "abc", "abcd"}

// Create a new array list with the lengths of the strings. 
var lengthsOnly = myStrings.map(\ str -> str.length)

After the preceding code executes, the variable lengthsOnly is an array list, with elements 1, 1, 2, 2, 3, and 4.

Implicit type inference

In the preceding example, the map method takes a function that converts a String to its length. The code does not declare the type of the block argument str explicitly. At compile time, str is statically typed by inference as a String argument, from the declaration of the variable myStrings. That declaration uses the generics syntax ArrayList<String> to specify an ArrayList of String objects.

Similarly, the lengthsOnly variable is statically typed by inference, from the type returned by the map method. The block function passed to the map method returns an Integer, so the map method returns as an ArrayList of Integer objects.

Explicit type declaration

Although implicit type inference makes type declarations for you automatically, declare the types explicitly to increase the clarity of your code. For example, the following Gosu code declares the types for the block argument str and the type of object returned by the map method.

// Declare and initialize an array list of strings. 
var myStrings = new ArrayList<String>(){"a", "b", "bb", "ab", "abc", "abcd"}

// Create a new array list with the lengths of the strings. 
var lengthsOnly : List<Integer> as ArrayList = myStrings.map(\ str:String -> str.length)

The type declaration for the argument to the block uses the declaration :String. The type declaration for the object that map method returns is more complex. The code declares that the map method returns an object that implements the List interface, with the type declaration : List<Integer>. The code downcasts the type of the returned object to an ArrayList, with the as keyword.

Note: The downcast to ArrayList is for clarity only. By convention, the Gosu compiler assumes that a type declaration of List<T> is a declaration of ArrayList<T>.

See also