Reputation: 9986
I want to fill list with objects from java.util.Iterator
. There is a simple java-like code in groovy source file.
def itr = reader.read()
List<FooRecord> ret = new ArrayList<FooRecord>()
while (itr.hasNext()) {
FooRecord rs = itr.next()
ret.add(rs)
}
Is there groovier way to perform copy from Iterator
to list?
Upvotes: 1
Views: 536
Reputation: 4482
or just use the as
keyword in groovy:
def myList = itr as List
thus the following code:
def list1 = [1, 2, 3]
def itr = list1.iterator()
println itr.class.name
println itr instanceof Iterator
def list2 = itr as List
println "list2: $list2"
println "list2 class: ${list2.class.name}"
prints out:
java.util.ArrayList$Itr
true
list2: [1, 2, 3]
list2 class: ArrayList$Itr1_groovyProxy
Upvotes: 0
Reputation: 17
have you thought using a for() instead of a while?, what about instantiating your class before the while? like this?
def itr = reader.read()
List<FooRecord> ret = new ArrayList<FooRecord>()
FooRecord rs = new FooRecord();
while (itr.hasNext()) {
rs = itr.next()
ret.add(rs)
}
Upvotes: 0