Search code examples
arraylistgroovytreemap

How to create TreeMap of ArrayList in Groovy


I've created an ArrayList by looping over an array of values, which creates an array in the "common" key/value structure.

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

The array looks like the following:
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']

Asking for the class of this via timeWithIdentifier.getClass() I get the following result java.util.ArrayList.

Now I want to put the above key/value combination in a new TreeMap by using the following: treeMapTime = new TreeMap<Integer, Long>(timeWithIdentifier )

Unfortunately I get the following error

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

What am I missing about it?


Solution

  • tl;dr:

    Here's how it should be done:

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

    Explanation:

    As can be seen here TreeMap doesn't take an ArrayList as constructor argument - Map should be passed.

    When processing items with for loop you're not creating instances of Maps but strings. Change timeWithIdentifier to an instance of Map an add item under i key. Then pass whole timeWithIdentifier as an argument TreeMap constructor. It can be even easier:

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