mastahb mastahb - 1 year ago 78
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 = [
// 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) {
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 Source

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() ? : null }

def clos = closure()

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

Which prints:


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download