Luciano
Luciano

Reputation: 8582

Enhanced collections methods on an Iterator

Is it possible to use the enhanced Collections methods that Groovy provides, like findAll and Collect with an iterator (of class java.util.Iterator) ?

Upvotes: 1

Views: 908

Answers (1)

ataylor
ataylor

Reputation: 66069

Most of the enhanced methods (including findAll and collect) do work with iterators. You can test it out in the console:

assert [1,2,3].iterator().findAll{ it % 2 } == [1,3]
assert [1,2,3].iterator().collect{ it * 2 } == [2,4,6]

Check out DefaultGroovyMethods for a list of the extra methods groovy provides. In general, whenever your class is an instance of the first arg's type, that method applies to your class. In the case of collect and findAll, iterator uses the Object version. Others, like collectMany have an iterator specific version.

Upvotes: 6

Related Questions