From the Groovy JDK:
Iterates over the collection of items which this Object represents and returns each item that matches using the IDENTITY Closure as a filter - effectively returning all elements which satisfy Groovy truth.
Finds all items matching the IDENTITY Closure (i.e. matching Groovy truth).
Short answer: the result will be the same.
Long answer:
grep
normally uses a filter object, on which isCase
is then called. As such the argument to grep normally is no Groovy Closure. For findAll
you use a Closure as argument, and if the result of the Closure is evaluated to true, it is taken into the resulting collection.
Now it is important to know that a Closure has an isCase method as well. Closure#isCase(Object)
will execute the Closure using the argument as argument for the Closure and the result of it is then evaluated using Groovy Truth. For an identity Closure, ie. {it}
, this means the closure will return what is given to it, thus Groovy will apply Groovy Truth to the argument of the grep call. The result is then the same as with findAll.
Actually there is a slight difference between both. At least when using those methods with maps.
grep
returns an ArrayList
, when findAll
returns a Map
.
Here follows an example:
def l_map = [a:1, b:2, c:3]
def map_grep = l_map.grep { it.key == 'a' || it.value == 2}
def map_findAll = l_map.findAll { it.key == 'a' || it.value == 2}
println map_grep
println map_findAll
assert l_map instanceof Map
assert map_grep instanceof ArrayList
assert map_findAll instanceof Map
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