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?
Groovy - any() & every() Method any iterates through each element of a collection checking whether a Boolean predicate is valid for at least one element.
Return Value − The find method returns the first value found or null if no such element exists.
[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]
Groovy - findAll()It finds all values in the receiving object matching the closure condition.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With