如何在groovy中对列表进行排序

时间:2012-11-21 13:20:08

标签: groovy

我正在尝试排序数组列表

例如

def list = [1, 1, 4, 4, 3, 4, 1]

希望排序:

[1, 1, 1, 4, 4, 4, 3]

非常感谢。


我习惯了我的代码

例如

def plnProcessGoalInstance = ......someting    
def order = plnProcessGoalInstance.plnGoal.plnTargetPlan.id.unique() //[1, 4, 3,] ,plnProcessGoalInstance.plnGoal.plnTargetPlan.id = [1, 1, 4, 4, 3, 4, 1]
def plnProcessGoalInstance = plnProcessGoalInstance.sort{ a, b -> 
           order.indexOf(a.plnGoal.plnTargetPlan.id ) <=> order.indexOf(b.plnGoal.plnTargetPlan.id )}

非常感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

怎么样:

def order = [ 1, 4, 3 ]
def list = [ 1, 1, 4, 4, 3, 4, 1 ]

list.sort { a, b -> order.indexOf( a ) <=> order.indexOf( b ) }

assert list == [1, 1, 1, 4, 4, 4, 3]

或者,假设Deruijter的评论是正确的,并且您希望按频率降序排序,然后按照具有相同频率的那些按数字排序:

def list = [ 1, 1, 4, 4, 3, 4, 1 ]
def order = list.countBy { it }
                .sort { a, b -> 
                  b.value <=> a.value ?: a.key <=> b.key
                }.keySet().toList()
list.sort { a, b -> order.indexOf( a ) <=> order.indexOf( b ) }

countBy需要Groovy 1.8