56

Is there a .collect with an index? I want to do something like this:

def myList = [
    [position: 0, name: 'Bob'],
    [position: 0, name: 'John'],
    [position: 0, name: 'Alex'],
]

myList.collect { index ->
    it.position = index
}

(ie. I want to set position to a value which will indicate the order in the list)

5

6 Answers 6

118

Since Groovy 2.4.0 there is a withIndex() method which gets added to java.lang.Iterable.

So, in a functional fashion (no side effect, immutable), it looks like

def myList = [
  [position: 0, name: 'Bob'],
  [position: 0, name: 'John'],
  [position: 0, name: 'Alex'],
]

def result = myList.withIndex().collect { element, index ->
  [position: index, name: element["name"]] 
}
0
13

eachWithIndex would probably work better:

myList.eachWithIndex { it, index ->
    it.position = index
}

Using a collectX doesn't really seem necessary since you're just modifying the collection and not returning particular pieces of it into a new collection.

3
  • 13
    unless you need it to return a new collection
    – dstarh
    Feb 24, 2012 at 13:47
  • 1
    @dstarh - Right, but the question says "I want to set the position to a value", which would make the collection seem unnecessary.
    – Rob Hruska
    Feb 24, 2012 at 13:48
  • 4
    agreed, collect is probably not necessary in this case. Were it in a chain of other calls that would be different. I'd still however like to see a collect with index
    – dstarh
    Feb 24, 2012 at 13:50
13

Slightly groovier version of collectWithIndex:

List.metaClass.collectWithIndex = {body->
    def i=0
    delegate.collect { body(it, i++) }
}

or even

List.metaClass.collectWithIndex = {body->
    [delegate, 0..<delegate.size()].transpose().collect(body)
}
7

This should do exactly what you want

List.metaClass.collectWithIndex = {cls ->
    def i = 0;
    def arr = [];
    delegate.each{ obj ->
        arr << cls(obj,i++)
    }
    return arr
}



def myCol = [
    [position: 0, name: 'Bob'],
    [position: 0, name: 'John'],
    [position: 0, name: 'Alex'],
]


def myCol2 = myCol.collectWithIndex{x,t -> 
    x.position = t
    return x
}

println myCol2

=> [[position:0, name:Bob], [position:1, name:John], [position:2, name:Alex]]
0
5

Without adding any extension methods, you can do this in a pretty straightforward way:

def myList = [1, 2, 3]
def index = 0
def myOtherList = myList.collect {
  index++
}

It would certainly be useful for this method to exist automatically though.

2

Like dstarh said, unless you're looking for a non-destructive method that returns a new map with your indices populated, Rob Hruska's answer is what you're looking for.

dstarh's answer provides you the non-destructive version of collectWithIndex, but handles the actual collection of results too.

I usually find it best to delegate such heavy lifting to the receiving object so as to play nice with polymorphic collect implementations, i.e., in case a specific class implements collect differently (than just putting the results in an array), having collectWithIndex delegate to it will ensure uniform behaviour. Here's how the code would look:

@Category(List)
class Enumerator {
    def collectWithIndex(Closure closure) {
        def index = 0
        this.collect { closure.call(it, index++) }
    }
}

use(Enumerator) {
    ['foo', 'bar', 'boo', 'baz'].collectWithIndex { e, i ->
        [index: i, element: e]
    }
}

Refer to this gist for an example for both eachWithIndex and collectWithIndex.

Also, like the comments to your question state, there are two Jira issues open for the feature we've described- GROOVY-2838 & GROOVY-3797

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.