Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterator over an array in Groovy?

public class ArrayTest{
  public static void main(String[] args){
    String[] list = {"key1", "key2", "key3"};
    String[] list2 = {"val1", "val2", "val3"};

    for(int i = 0; i < list.length; i++){
      ilike(list[i], list2[i];        
    }
  }
}

How to write the above code in Groovy?

Actually, its a grails application where I want to do similar thing above.

like image 284
jai Avatar asked Jun 01 '11 10:06

jai


1 Answers

You have a couple of options that come to mind...

Given:

String[] list  = [ 'key1', 'key2', 'key3' ]
String[] list2 = [ 'val1', 'val2', 'val3' ]

Then you could do:

list.eachWithIndex { a, i ->
  ilike a, list2[ i ]
}

or assuming ilike is defined as:

void ilike( String a, String b ) {
  println "I like $a and $b"
}

Then you can do (using transpose):

[list,list2].transpose().each {
  ilike it
}
like image 69
tim_yates Avatar answered Nov 09 '22 06:11

tim_yates