2012-11-21 131 views
1

我嘗試對排列列表進行排序如何在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)} 

非常感謝您的幫助。

+4

你想在最後用3分類嗎?你能描述你的排序應該如何工作嗎? –

+1

看起來像要根據以下條件排序: A.特定數目的發生(降序) B.數量(升序) – Deruijter

+0

[1,2,3,4,1] - > [1,1,2,3, 4] [1,4,3,2,1] - > [1,1,4,3,2]同組groupBy –

回答

2

如何:

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