Manish Singhal
Manish Singhal

Reputation: 91

Loop over multiple List simultaneously in Groovy

I like to loop over multiple list simultaneously as below:

def p = ["A", "B", "C"]
def q = ["d", "f", "g"]
for (x,y in p,q) {

   println x
   println y

}

I can do something like below:

def p = ["A", "B", "C"]
def q = ["d", "f", "g"]
for (i=0; i<q.size(); i++) {

   println p[i]
   println q[i]

}

but I would love to know the solution in previous format. Any idea how to achieve the same in groovy?

Upvotes: 9

Views: 7135

Answers (1)

Opal
Opal

Reputation: 84756

You can try transpose:

def p = ["A", "B", "C"];
def q = ["d", "f", "g"];
for (i in [p,q].transpose()) {
    println i[0]
    println i[1]
}

Upvotes: 16

Related Questions