Dec 1st 2008 Groovy Makes Iteration Easy
Out of the box, groovy gives you a number of powerful methods to iterate over lists and maps:
def fibList = [1, 1, 2, 3, 5] fibList.each { println it } // prints all of the numbers in the list assert fibList.any { it == 3 } assert fibList.every { it > 0 } assert fibList.collect { it - 1 } == [0, 0, 1, 2, 4] assert fibList.findAll { it > 1 && it < 5 } == [2, 3] assert fibList.find { it > 1 } == 2 assert fibList.inject("fib: ") { str, val -> str << val }.toString() == "fib: 11235"
That’s really nice if you’re working with raw lists and maps, but what if you have a class that doesn’t extend list or map? How hard is it to empower that class with the groovy iteration methods? If this were Java, you’d likely need to implement an interface with these methods (and throw a “not implemented” exception for those you didn’t feel like taking the time to implement).
Since it’s not Java, but groovy (and you’ve read the title of this blog post :), you know it’s easy!
Read More »
7 Comments » Posted by tednaleid / grails and groovy and shortcut