如何用更具Groovy风格的方式将java.util.Iterator元素填充到List?
Absolutely! Groovy is all about cutting down boilerplate and writing concise, expressive code—so there are way cleaner alternatives to that Java-style loop for converting an Iterator to a List.
The Simplest, Most Groovy Way: toList() Extension Method
Groovy's GDK (Groovy Development Kit) adds handy extension methods to standard Java classes, including java.util.Iterator. The toList() method does exactly what you need in one line:
def itr = reader.read() List<FooRecord> ret = itr.toList()
You can even condense it further if you don't need to keep the iterator reference around:
List<FooRecord> ret = reader.read().toList()
Flexible Alternative: collect()
If you ever need to transform elements while converting them (like modifying a field on FooRecord before adding it to the list), collect() is perfect. Even for plain copying, it works seamlessly:
List<FooRecord> ret = itr.collect()
If you want to explicitly specify the list type (though Groovy's type inference usually makes this unnecessary), you can do:
List<FooRecord> ret = itr.collect([] as ArrayList<FooRecord>)
Why This Is Better
These methods eliminate the need for manual loop setup, variable tracking, and repetitive hasNext()/next() calls. They align with Groovy's philosophy of writing code that's readable, concise, and focused on what you want to achieve—not the mechanics of how to do it.
内容的提问来源于stack exchange,提问作者Loom

