3

我正在尝试对数组列表进行排序

例如。

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 )}

非常感谢您的帮助。

4

1 回答 1

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

于 2012-11-21T13:31:17.560 回答