Loom
Loom

Reputation: 9986

Fill list from java iterator

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

Answers (5)

ernest_k
ernest_k

Reputation: 45319

You can run a for-each on the iterator:

itr.each{ret << it}

Upvotes: 2

Matias Bjarland
Matias Bjarland

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

daggett
daggett

Reputation: 28564

def s = '12345'
def List<String> f=s.iterator().collect{it}

Upvotes: 0

Loom
Loom

Reputation: 9986

def ret = []
ret.addAll(reader.read())

Thanks to JB Nizet

Upvotes: 0

Cesar Kemper
Cesar Kemper

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

Related Questions