Groovy difference between 'any' and 'find' methods
In groovy, there are two methods namely any
and find
method that c开发者_JAVA百科an 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?
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.
(!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
}
精彩评论