Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Groovy Gotcha With the Every() Collection Method

DZone's Guide to

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 ·
Free Resource

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Download Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

Topics:
method ,collection ,groovy ,value ,programming ,gotcha ,object ,iterable ,interface

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}