Finding data in collections

Gosu provides the firstWhere, where, and lastWhere methods to enable you to find items in collections that match certain criteria. These functions can be very processor intensive, so be careful how you use them. Consider whether other approaches may be better, testing your code as appropriate.

The where method takes a block as a parameter. In turn, this block takes an element as a parameter. The block has a Boolean expression in its body that uses the element and evaluates this expression to true or false. In the case that the Boolean expression evaluates to true, the block returns the element.

When you call the where method, the block executes once for each element in a collection of elements. In executing, the block evaluates the Boolean expression for each such element. The block returns all elements for which the Boolean expression evaluates to true. In this way, the where method forms a new collection of elements. The method then returns this new collection. If the where method finds no matching items, it returns null.

The following example demonstrates how to find all items that match a criterion:

var strs = new ArrayList<String>(){"a", "ab", "abc"}
var longerStrings = strs.where( \ str -> str.length >= 2 )

The value of longerStrings is {"ab", "abc"}. The expression str.length >= 2 is true for both of them.

The firstWhere method takes a block as a parameter. As in the case of the where method, this block takes an element as a parameter, evaluates a Boolean expression body for the element, and returns the element in the case that the expression evaluates to true. The firstWhere method returns the first element that the block returns. If the firstWhere method finds no matching items, it returns null.

The following example demonstrates how to find the first item that matches a criterion:

var strs = new ArrayList<String>(){"a", "ab", "abc"}
var firstLongerStr = strs.firstWhere( \ str -> str.length >= 2 )

The value of firstLongerStr is "ab" because "ab" is the first element in the list for which str.length >= 2 evaluates to true.

The lastWhere method operates in a similar manner as the where and firstWhere methods. If the lastWhere method finds no matching items, it returns null.