如何在 Groovy 中创建 ArrayList 的 TreeMap

How to create TreeMap of ArrayList in Groovy

我通过遍历值数组创建了一个 ArrayList,它在 "common" key/value 结构中创建了一个数组。

def timeWithIdentifier = []
for (i = 0; i <= time.size()-1; i++) {
     timeWithIdentifier [i] = i + ":'" + time[i] + "'";
}

数组如下所示:
timeWithIdentifier = [0:'1423734900000', 1:'1423735200000', 2:'1423735500000', 3:'1423735800000', 4:'1423736100000', 5:'1423736400000', 6:'1423736700000', 7:'1423737000000', 8:'1423737300000', 9:'1423737600000', 10:'1423737900000', 11:'1423738200000', 12:'1423738500000', 13:'1423738800000', 14:'1423739100000', 15:'1423739400000', 16:'1423739700000', 17:'1423740000000', 18:'1423740300000', 19:'1423740600000', 20:'1423740900000', 21:'1423741200000', 22:'1423741500000', 23:'1423741800000', 24:'1423742100000', 25:'1423742400000']

通过 timeWithIdentifier.getClass() 请求 class 我得到以下结果 java.util.ArrayList.

现在我想通过使用以下内容将上述 key/value 组合放入新的 TreeMap 中:treeMapTime = new TreeMap<Integer, Long>(timeWithIdentifier )

不幸的是我收到以下错误

groovy.lang.GroovyRuntimeException: Could not find matching constructor for: java.util.TreeMap(java.util.ArrayList)

我错过了什么?

tl;博士:

操作方法如下:

def time = (1..10)
def timeWithIdentifier = [:]
for (i = 0; i <= time.size()-1; i++) {
     timeWithIdentifier[i] = time[i]
}

new TreeMap(timeWithIdentifier)

解释:

可以看出 here TreeMap 没有将 ArrayList 作为构造函数参数 - Map 应该被传递。

当使用 for 循环处理项目时,您创建的不是 Maps 的实例,而是字符串。将 timeWithIdentifier 更改为 Map 的实例,并在 i 键下添加项目。然后将整个 timeWithIdentifier 作为参数传递给 TreeMap 构造函数。它可以更简单:

def time = (1..10)
def timeWithIdentifier = [:] as TreeMap
for (i = 0; i <= time.size()-1; i++) {
     timeWithIdentifier[i] = time[i]
}