Question

I have a question why using collect to a string array is not working.

This is working ok

String[][] serversAndQueues = [["server1","queue"],["server1","queue1"],["server2","queue2"]]

serversAndQueues.groupBy { it[ 0 ] }.each { server, value ->
    def queues = []
    value.collect(queues){
        it[1]
    }
    println "$server => $queues"
}

OUTPUT

server1 => [queue, queue1]
server2 => [queue2]

but if I try to define the queues as a string array def queues = [] as String[], an exception is trown

String[][] serversAndQueues = [["server1","queue"],["server1","queue1"],["server2","queue2"]]

serversAndQueues.groupBy { it[ 0 ] }.each { server, value ->
    def queues = [] as String[]
    value.collect(queues){
        it[1]
    }
    println "$server => $queues"
}

OUTPUT

Exception thrown

    groovy.lang.MissingMethodException: No signature of method: java.util.ArrayList.collect() is applicable for argument types: ([Ljava.lang.String;, ConsoleScript40$_run_closure2_closure3) values: [[], ConsoleScript40$_run_closure2_closure3@ff8c2a]
    Possible solutions: collect(), collect(), collect(groovy.lang.Closure), collect(java.util.Collection, groovy.lang.Closure), collect(java.util.Collection, groovy.lang.Closure), collect(groovy.lang.Closure)

        at org.codehaus.groovy.runtime.ScriptBytecodeAdapter.unwrap(ScriptBytecodeAdapter.java:55)

        at org.codehaus.groovy.runtime.callsite.PojoMetaClassSite.call(PojoMetaClassSite.java:46)
    ..
    ...
Was it helpful?

Solution

You can't collect into an array, only a Collection

You could try

def queues = value.collect { it[ 1 ] } as String[]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top