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

Navigate the Maze of the End-User Experience and pick up this APM Essential guide, brought to you in partnership with CA Technologies

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.

Thrive in the application economy with an APM model that is strategic. Be E.P.I.C. with CA APM.  Brought to you in partnership with CA Technologies.

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

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}