Overview of collections

Gosu provides several features for usage of collections like lists and maps. Gosu directly uses the built-in Java collection classes like java.util.ArrayList and java.util.Hashmap. This usage makes Gosu straightforward to use for interaction with pre-existing Java classes and libraries.

In addition, Gosu adds the following features:

  • Shorthand syntax for creating lists and maps that is natural to read and still uses static typing:
    var myList = { "aa", "bb }
    var myMap = { "a" -> "b", "c" -> "d" }
  • Shorthand syntax for getting and setting elements of lists and maps
    var myList = { "aa", "bb" }
    myList[0] = "cc"
    var myMap = { "a" -> "b", "c" -> "d" }
    var mappedToC = myMap["c"]
  • Gosu includes enhancements that improve Java collection classes. Some enhancements enable you to use Gosu features that are unavailable in Java. For example, the following Gosu code initializes a list of String objects and then uses enhancement methods that use Gosu blocks, which are in-line functions.
    // Use Gosu shortcut to create a list of type ArrayList<String>
    var myStrings = { "a", "abcd", "ab", "abc" }
    
    // Sort the list by the length of the String values:
    var resortedStrings = myStrings.sortBy(\ str -> str.length)
    
    // Iterate across the list and run arbitrary code for each item:
    resortedStrings.each(\ str -> print(str))

Notice how the collection APIs are chainable. Alternatively, for readability, you can put each step on a separate lines. The following example declares some data, then uses a block to search for a subset of the items, and then sorts the results.

var minLength = 4
var strings = { "yellow", "red", "blue" }
var sorted = strings.where(\ s -> s.length() >= minLength).sort()
print(sorted)

See also