0

我有一个问题,为什么对字符串数组使用 collect 不起作用。

这工作正常

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"
}

输出

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

但是如果我尝试将队列定义为字符串数组def queues = [] as String[],则会出现异常

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"
}

输出

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)
    ..
    ...
4

1 回答 1

1

你不能收集到一个数组中,只有一个 Collection

你可以试试

def queues = value.collect { it[ 1 ] } as String[]
于 2013-11-28T13:35:23.360 回答