Groovy list.sort by first, second then third elements

前端 未结 7 1243
旧时难觅i
旧时难觅i 2021-02-02 09:42

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, th

7条回答
  •  情深已故
    2021-02-02 10:04

    you can use kobo-commons' CollectionUtils library.

    https://github.com/kobo/kobo-commons/wiki/sort-by-multiple-keys

    import org.jggug.kobo.commons.lang.CollectionUtils
    
    CollectionUtils.extendMetaClass()
    
    
    list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]
    list = list.sort{ [ it[0], it[1], it[2] ]} // sort by multiple keys
    assert list == [[1, 0, 3], [1, 5, 2], [2, 0, 1]]
    
    list2 = [ [name:"a", age:13], [name:"a",age:15], [name:"b", age:13] ]
    list2 = list2.sort{[it.name, it.age] } // sort by name and age
    assert list2 == [[name:"a", age:13], [name:"a", age:15], [name:"b", age:13]]
    

提交回复
热议问题