Created
June 24, 2011 09:20
-
-
Save snackycracky/1044484 to your computer and use it in GitHub Desktop.
groovy inject examples from http://groovy.codehaus.org/groovy-jdk/java/util/Collection.html#inject(U,%20groovy.lang.Closure)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
inject | |
public Object inject(Object initialValue, Closure closure) | |
Iterates through the given Collection, passing in the initial value to the 2-arg closure along with the first item. The result is passed back (injected) into the closure along with the second item. The new result is injected back into the closure along with the third item and so on until the entire collection has been used. Also known as foldLeft in functional parlance. Examples: | |
assert 1*1*2*3*4 == [1,2,3,4].inject(1) { acc, val -> acc * val } | |
assert 0+1+2+3+4 == [1,2,3,4].inject(0) { acc, val -> acc + val } | |
assert 'The quick brown fox' == | |
['quick', 'brown', 'fox'].inject('The') { acc, val -> acc + ' ' + val } | |
assert 'bat' == | |
['rat', 'bat', 'cat'].inject('zzz') { min, next -> next < min ? next : min } | |
def max = { a, b -> [a, b].max() } | |
def animals = ['bat', 'rat', 'cat'] | |
assert 'rat' == animals.inject('aaa', max) | |
Visual representation of the last example above: | |
initVal animals[0] | |
v v | |
max('aaa', 'bat') => 'bat' animals[1] | |
v v | |
max('bat', 'rat') => 'rat' animals[2] | |
v v | |
max('rat', 'cat') => 'rat' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment