Groovy list.sort by first, second then third elements

Viewed 29416

I have a groovy list of lists i.e.

list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]

I would like sort it by order of the first element, then second, then third.

Expected

assert list == [[1, 0, 3], [1, 5, 2], [2, 0, 1]]

I started with list = list.sort{ a,b -> a[0] <=> b[0] } but that only sorts the first element. How do you finish?

Thanks

8 Answers

You can do it in one line:

list.sort { String.format('%010d%010d%010d', it[0], it[1], it[2]) }

I know I'm very late to the party but I wanted a way to sort by multiple keys, asc or desc separately for each field. I came up this this method which seems to work:

public static sortObjectArray(def objects, Map sortFields){
    objects.sort{a,b->
        int matches = 0
        for(def entry in sortFields){

            if(entry.value == 'asc'){
                matches = (a[entry.key] <=> b[entry.key]).toInteger()
            }else{
                matches = (b[entry.key] <=> a[entry.key]).toInteger()
            }

            if(matches != 0){
                break
            }
        }

        return matches
    }
}

It allows for passing an object list and a map, the object list will be sort by the keys of the map, either descending or ascending based on the value of the map entry. Ex:

ArrayList<Map> objects = [
        [field1:1,field2:2,field3:2],
        [field1:1,field2:1,field3:1],
        [field1:1,field2:2,field3:1],
]

println sortObjectArray(objects,[field1:'asc',field2: 'desc',field3: 'asc'])

Outputs:

[[field1:1, field2:2, field3:1], [field1:1, field2:2, field3:2], [field1:1, field2:1, field3:1]]
Related