Grooovier Ways to Iterate Through Lists (Mark Palmer)
Groovy June 16th, 2007
There’s been a lot of people asking for a Java loop syntax in groovy. A lot if not almost all usages however are cleaner without it, once you know some idiomatic groovy.
Here are just some of the examples of looping constructs available in groovy:
def results = []
10.times { results << it }
assert results == [0,1,2,3,4,5,6,7,8,9]
results = []
0.step(10, 2) { results << it }
assert results == [0,2,4,6,8]
results = []
(1..10).each { results << it }
assert results == [1,2,3,4,5,6,7,8,9,10]
results = []
(1..10).step(2) { results << it }
assert results == [1,3,5,7,9]
def items = [‘one’, ‘two’, ‘three’, ‘four’]
results = []
items.eachWithIndex { item, idx ->
results << idx
}
assert results == [0,1,2,3]
There are a whole range of Groovy features at work here, from inline lists to ranges, GDK methods added to JDK classes such as step() on numeric types and of course closures.
Tags: Groovy
About
Leave a Comment