Iterating across collections

Suppose you want to print each element in a list. You could use the list method each, which can be used instead of a traditional Gosu for loop. The following example Gosu code chains the map and each functions to create a new list and process each element in the new list in a single Gosu statement.

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

// Create a new list with the lengths of the strings and 
// iterate the new list to print each element
myStrings.map(\ str -> str.length).each(\ len -> print(len)) // Two methods chained in one statement

Use the each method to perform repeated actions with the elements in a collection.

You can achieve concise code by chaining the map and each methods in a single Gosu statement. Sometimes, the conciseness of method chaining makes your code hard for others to read and interpret. In these cases, you might instead assign the return value of the map method to a variable, and then call the each method on the variable. For example:

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

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

// Iterate the new list to print each element. 
strLengths.each( \ len -> print( len ) )

Method chaining discards the new list after executing the statement that includes the map method. If you need to access the new list returned by the map method later in your code, assign the return value to a variable.