I have an array of 'tasks' that I am getting back from a JSON response that I am iterating through, and doing some processing on each task. Here is so开发者_运维百科me psudocode:
def tasks = grails.converters.JSON.parse(json response)
tasks.each() {task ->
//do some processing here
}
On the very last task in the list, I want to run an additional operation. I'm looking for a built in way to do this in grails/groovy. My searches have thus far yielded no results.
Another possible solution is
tasks.eachWithIndex() { task, i ->
//whatever
if(i == tasks.size() - 1){
//something else
}
}
Another method might be to do something along the lines of:
tasks[0..-1].each {
// Processing for all but last element
}
tasks[-1 ].each {
// Processing for last element
}
Of course, if there's only one element in the tasks
list, then it will get both processing applied to it (and if there are no elements in the list, it will crash) :-/
edit
An alternative (which may not be considered as easily readable), is as follows:
// 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 ) }
After running this, output
is equal to:
[Start a, Start b, Final c]
And this works with task lists with just one item
I think what you need is along the lines of:
tasks.each() {task ->
//do some processing here
}
tasks[-1].doSomethingElse()
(provided tasks.size() > 0).
The [-1] syntax means last in the list.
精彩评论