Groovy difference between 'any' and 'find' methods

11,305

Solution 1

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.

Solution 2

 (!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

Share:
11,305
Ant's
Author by

Ant's

Updated on July 19, 2022

Comments

  • Ant's
    Ant's almost 2 years

    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?