Over a million developers have joined DZone.

Groovy Gotcha With the Every() Collection Method

Author Brian Swartzfager outlines for us a gotcha when using Groovy's every() method in collections. Read on for details.

· Java Zone

What every Java engineer should know about microservices: Reactive Microservices Architecture.  Brought to you in partnership with Lightbend.

In the Groovy programming language, every object that implements the Iterable interface (such as List and Map objects) comes with the every() method.  The every() method takes a closure as an argument and is supposed to evaluate whether every item in the collection meets the condition set forth in the closure:

assert [ 3, 4 ].every{ element -> element > 2 }  //true
assert [ fingerCount: 10, toeCount: 10 ].every{ key, value -> value == 10 } //true

Given that, you might reasonably expect that the every() method would return false when executed against an empty collection. But it doesn't:

assert [].every{ element -> element > 2 }  //true
assert [ : ].every{ key, value -> value == 10 }  //true 

There is a JIRA ticket about this issue: https://issues.apache.org/jira/browse/GROOVY-7207. The initial commenter's guess is probably correct: that the every() method starts with a default return value of true and only becomes false if and when an item in the collection fails the conditional test, so an empty collection fails to affect the default value of true.

Still, it's not what I would have expected, and I was unaware of the behavior until I encountered it for myself.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture, a free O'Reilly book. Brought to you in partnership with Lightbend.


Published at DZone with permission of Brian Swartzfager, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}