mastahb mastahb - 2 months ago 8
Groovy Question

Return items one by one from groovy list

Im pretty new to Groovy and I'm struggling a little. I have got a List and I want to return the items in the list 1 by 1 each time I call the function

def list = [
"blog1",
"blog2",
"blog3"
]
// Result variable for storing loop results.
def result = ''
// Closure to fill result variable with value.
def createResult = {
if (!it) { // A bit of Groovy truth: it == 0 is false
result = '0'
} else {
result += it
}
}

// Groovy for-each loop.
for (i in list) {
createResult(i)
}
return result


Now I get back the following value: blog1blog2blog3

I would like to see:

First call of this code return blog 1, 2nd call of the function return blog 2 etc.

How to solve this?

Answer

You're describing an Iterator

If you want a closure that wraps an iterator and handles the end of the list without an exception, you could do:

def closure = { ->
    def i = ['item1', 'item2', 'item3'].iterator();
    { -> i.hasNext() ? i.next() : null }
}

def clos = closure()

println clos()
println clos()
println clos()
println clos()

Which prints:

item1
item2
item3
null

Not 100% sure that's what you want though, it's hard to tell from the question...