Blocks and collections

Gosu blocks are particularly useful for working with collections of objects. Blocks support concise, readable code that loops across items, extracts information from every item in a collection, or sorts items. Common collection enhancement methods that use blocks are map, each, and sortby.

For example, suppose you want to sort the following list of String objects:

var myStrings = new ArrayList<String>(){"a", "abcd", "ab", "abc"}

You can use blocks to sort the list based on various attributes, such as the length of the strings. Create a block that takes a String and returns the sort key, which in this case is the String object’s length. The built-in list sortBy(...) method handles the rest of the sorting algorithm and then returns the new sorted array:

var resortedStrings = myStrings.sortBy( \ str -> str.length() )

These block-based collection methods are implemented using a built-in Gosu enhancement of the Java language List class.

See also