开发者

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 wan开发者_运维百科t to do similar thing above.


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
}


I am not sure what iLike will be doing but from the implementation of your original Java code I feel that you might consider using hash map and your program would look like following

def map= ['key1':'val1', 'key2':'val2', 'key2':val2, "key3":'val3']
map.eachWithIndex{ it, i-> //eachIndex() always takes 2 params
  ilikeit it.key, it.value // and you have i if you need it in your program
}

Following might be a good reference point for youhttp://groovy.codehaus.org/JN1035-Maps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜