Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy difference between 'any' and 'find' methods

Tags:

groovy

In groovy, there are two methods namely any and find method that can be used in Maps.

Both these methods will "search" for the content that we are interested in (that is, both any and find method return whether the element is in Map or not, that is they need to search).

But within this search how do they differ?

like image 708
Ant's Avatar asked Mar 01 '11 13:03

Ant's


People also ask

What is any in groovy?

Groovy - any() & every() Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element.

What does find return in groovy?

Return Value − The find method returns the first value found or null if no such element exists.

What does [:] mean in groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

What is find findAll and it in groovy?

Groovy - findAll()It finds all values in the receiving object matching the closure condition.


2 Answers

They actually do different things. find returns the actual element that was found whereas any produces a bool value. What makes this confusing for you is the groovy truth.

Any unset (null?) value will resolve to false

def x
assert !x

So if you are just checking for false, then the returned values from both methods will serve the same purpose, since essentially all objects have an implicit existential boolean value.

like image 141
MojoFilter Avatar answered Nov 15 '22 08:11

MojoFilter


 (!list.find{predicate}) <> (!list.any{predicate})

However :

( list.find{predicate}) >< (list.any{predicate})

If any does not exist in Groovy API and you want to add this feature to List metClass, any implementation will be :

java.util.List.metaClass.any={Closure c-> 
     return delegate.find(c) != null

}

Find is more general than any

like image 30
Abdennour TOUMI Avatar answered Nov 15 '22 09:11

Abdennour TOUMI