Reputation: 177
i'm try to sort array list
eg.
def list = [1, 1, 4, 4, 3, 4, 1]
hope to sort :
[1, 1, 1, 4, 4, 4, 3]
Thank you very much.
i'm used to my code
eg.
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 )}
Thank you very much for help.
Upvotes: 3
Views: 4461
Reputation: 171074
How about:
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]
Or, assuming the comment by Deruijter is correct and you want to sort by descending frequency and then by number for those with the same freq:
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
requires Groovy 1.8
Upvotes: 3