Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between Groovy's non-argument grep() and findAll() methods?

Tags:

groovy

From the Groovy JDK:

public Collection grep()

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.

public Collection findAll()

Finds all items matching the IDENTITY Closure (i.e. matching Groovy truth).

like image 322
Armand Avatar asked May 22 '12 14:05

Armand


2 Answers

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.

like image 85
blackdrag Avatar answered Nov 01 '22 11:11

blackdrag


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
like image 6
Pedro Witzel Avatar answered Nov 01 '22 11:11

Pedro Witzel