在Grails中的each()中的最后一项上运行命令

时间:2011-07-07 15:27:23

标签: grails groovy each

我有一系列“任务”,我正在从我正在迭代的JSON响应中获取,并对每个任务进行一些处理。这是一些psudocode:

def tasks = grails.converters.JSON.parse(json response)
tasks.each() {task ->
  //do some processing here
}

在列表中的最后一个任务中,我想运行一个额外的操作。我正在寻找一种内置的方式来实现grails / groovy。到目前为止,我的搜索没有产生任何结果。

3 个答案:

答案 0 :(得分:7)

另一种可能的解决方案是

tasks.eachWithIndex() { task, i ->
//whatever
   if(i == tasks.size() - 1){
      //something else
   }
}

答案 1 :(得分:1)

另一种方法可能是做一些事情:

tasks[0..-1].each {
  // Processing for all but last element
}
tasks[-1   ].each {
  // Processing for last element
}

当然,如果tasks列表中只有一个元素,那么它将同时应用两个处理(如果列表中没有元素,它将崩溃): - /


修改

另一种选择(可能不被认为易于阅读)如下:

// A list of 'tasks' in our case Strings
tasks = [
  'a', 'b', 'c'
]

// Create a list of Closures the length of our list of tasks - 1
processing = (1..<tasks.size()).collect { { task -> "Start $task" } }
// Append a Closure to perform on the last item in the list
processing << { task -> "Final $task" }

// Then, transpose these lists together, and execute the Closure against the task
def output = [tasks,processing].transpose().collect { task, func -> func( task ) }

运行此操作后,output等于:

[Start a, Start b, Final c]

这适用于只有一个项目的任务列表

答案 2 :(得分:0)

我认为你需要的是:

tasks.each() {task ->
  //do some processing here
}
tasks[-1].doSomethingElse()

(提供的tasks.size()&gt; 0)。

[-1]语法表示列表中的最后一个。