Groovy list.sort by first, second then third elements

前端 未结 7 1179
旧时难觅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:01

    You should be able to iterate through the desired sorting in reverse order:

    list = [[2, 0, 1], [1, 5, 2], [1, 0, 3]]
    
    list = list.sort{ a,b -> a[2] <=> b[2] }
    list = list.sort{ a,b -> a[1] <=> b[1] }
    list = list.sort{ a,b -> a[0] <=> b[0] }
    
    assert list == [[1, 0, 3], [1, 5, 2], [2, 0, 1]]
    

    Each should override the previous just enough to keep the combined sorting intact.


    You can also chain them in order with the Elvis operator, ?:, which will defer to the next comparison when the previous are equal (and <=> returns 0):

    list.sort { a,b -> a[0] <=> b[0] ?: a[1] <=> b[1] ?: a[2] <=> b[2] }
    

提交回复
热议问题