Armand
Armand

Reputation: 24343

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

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).

Upvotes: 26

Views: 4111

Answers (2)

Pedro Witzel
Pedro Witzel

Reputation: 368

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

Upvotes: 6

blackdrag
blackdrag

Reputation: 6508

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.

Upvotes: 24

Related Questions