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?
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}
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 }
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:
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:
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]
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With