Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom List sorting

Tags:

groovy

Hi I have a list which contains elements [daily,monthly,weekly] or [monthly,weekly,daily] or [weekly,daily]

I need to sort the list in such a way that

[daily,monthly,weekly] == [daily,monthly,weekly]

[monthly, weekly, daily] == [daily, monthly, weekly]

[weekly, daily] == [daily, weekly]

Can some one please help me in this

like image 549
Siva Avatar asked Oct 20 '25 02:10

Siva


1 Answers

Assuming you mean that you have a list of Strings, then this should work:

customSorter = { 
  [ 'daily', 'monthly', 'weekly' ].indexOf( it )
}

assert [ 'daily', 'monthly', 'weekly' ].sort( customSorter ) == [ 'daily', 'monthly', 'weekly' ]
assert [ 'monthly', 'weekly', 'daily' ].sort( customSorter ) == [ 'daily', 'monthly', 'weekly' ]
assert [ 'weekly', 'daily' ].sort( customSorter ) == [ 'daily', 'weekly' ]

Or you could do this (to avoid repeatedly creating a List)

customSorter = { a, b, order=['daily','monthly','weekly'] ->
  order.indexOf( a ) <=> order.indexOf( b )
}
like image 73
tim_yates Avatar answered Oct 22 '25 05:10

tim_yates