The GDK methods

The GDK adds methods to every collection, and they replace most loops a Java program writes. Each one takes a closure and returns a collection, a value or a map.

Transform and filter

transform.groovy

def numbers = [5, 3, 8, 1, 9, 2] println numbers.collect { it * 2 } println numbers.findAll { it > 3 } println numbers.findAll { it % 2 == 0 }.collect { it * 10 } println numbers.collect { int n -> n % 2 == 0 ? 'even' : 'odd' }

groovy transform.groovy

[10, 6, 16, 2, 18, 4]
[5, 8, 9]
[80, 20]
[odd, odd, even, odd, odd, even]

collect transforms every element and findAll keeps the ones the closure accepts, so a chain of the two is a filter and a map in one line.

Reduce to one value

reduce.groovy

def numbers = [5, 3, 8, 1, 9, 2] println numbers.sum() println numbers.inject(0) { int total, int n -> total + n } println numbers.inject(1) { int total, int n -> total * n } println numbers.max() println numbers.min() println numbers.count { it > 4 } println numbers.average()

groovy reduce.groovy

28
28
2160
9
1
3
4.6666666667

inject carries a value from one element to the next, which is a sum, a product or a string built from the parts. average divides two sums and returns a BigDecimal.

Group and order

group.groovy

def words = ['pear', 'fig', 'apple', 'kiwi', 'plum'] println words.groupBy { it.length() }.sort() println words.sort { String a, String b -> a.length() <=> b.length() } println words.unique { String a, String b -> a.length() <=> b.length() } println words.max { it.length() } println words.take(2) println words.drop(2)

groovy group.groovy

[3:[fig], 4:[pear, kiwi, plum], 5:[apple]]
[fig, pear, kiwi, plum, apple]
[fig, pear, apple]
apple
[fig, pear]
[apple]

groupBy builds a map from the key the closure returns, and sort() on that map orders it by key so the print is stable. A comparator closure of two parameters orders the list; unique with the same comparator keeps the first of each group.

Related

Article author: Arthur Isaev