You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用更具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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:23:43