Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over multiple List simultaneously in Groovy

Tags:

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?

like image 297
Manish Singhal Avatar asked Mar 22 '17 11:03

Manish Singhal


People also ask

How do you iterate over a list in Groovy?

Lets start by looking at the two methods for iterating over a list. The each() method accepts a closure and is very similar to the foreach() method in Java. Groovy passes an implicit parameter it which corresponds to the current element in each iteration: def list = [1,"App",3,4] list.each {println it * 2}

How to use each () method in Groovy?

The each () method accepts a closure and is very similar to the foreach () method in Java. Groovy passes an implicit parameter it which corresponds to the current element in each iteration: def list = [ 1, "App", 3, 4 ] list.each {println it * 2 }

How to compare two lists in Groovy?

Groovy uses the “==” operator to compare the elements in two lists for equality. Continuing with the previous example, on comparing cloneList with arrlist the result is true: Now, let's look at how to perform some common operations on lists. 3. Retrieving Items from a List We can get an item from a list using the literal syntax such as:

How do I create a linked list in Groovy?

By default, Groovy creates an instance of java.util.ArrayList. However, we can also specify the type of list to create: def linkedList = [ 1, 2, 3] as LinkedList ArrayList arrList = [ 1, 2, 3] Next, lists can be used to create other lists by using a constructor argument:


1 Answers

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]
}
like image 180
Opal Avatar answered Sep 28 '22 05:09

Opal