I realize there is support for #each
Book.findAll().each(){ book->
println ">>> ${book}"
}
and there's even support for #inject
def sentence = m.inject('Message: ') { s, k, v ->
s += "${k == 'likes' ? 'loves' : k} $v "
}
Is there support for #map for Groovy out of the box (without any special libraries like Functional Java)?
def list = [1,2,3,4].map{ num->
num + 1
}
assert list == [2,3,4,5]
Apache Groovy is a Java-syntax-compatible object-oriented programming language for the Java platform. It is both a static and dynamic language with features similar to those of Python, Ruby, and Smalltalk.
Syntax. The syntax of Ruby is broadly similar to that of Perl and Python.
Groovy OverviewGroovy includes features found in Python, Ruby, and Smalltalk, but uses syntax similar to the Java programming language.
Programmers are also offered a level of abstraction by making use of a programming language like Ruby, which is written in C, which translates to Assembly language, which translates to machine language to translate 0s and 1s into something the computer understands.
You want collect
.
groovy:000> [1,2,3,4].collect { num -> num + 1 }
===> [2, 3, 4, 5]
I hope that helps.
You can use collect, as in
[1, 2, 3, 4].collect { it + 1 }
For the case where you're calling a method directly on each object in the collection there's a shorter syntax using the spread-dot operator:
[1, 2, 3, 4]*.plus 1
(using a method Groovy adds to java.lang.Integer to implement the +
operator)
This operator works even if the list contains nulls:
groovy:000> [1, 2, 3, null, 4]*.plus 1
===> [2, 3, 4, null, 5]
where with collect you'd have to check:
[1, 2, 3, null, 4].collect { it?.plus 1 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With