Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Groovy list is sorted in Ascending order, Sort it in Descending order and Vice Versa

Tags:

groovy

I have a groovy list of Order object. I want to sort this list on order id. If my list is sorted in ascending order then sort it in descending and Vice Versa. What is the smarted way to solve this problem?

like image 917
Ahmad.Masood Avatar asked Dec 02 '13 11:12

Ahmad.Masood


1 Answers

class Order {
    int id
    String toString() { "O$id" }
}

def list = [ new Order( id: 1 ), new Order( id: 2 ), new Order( id: 3 ) ]

// Sort ascending (modifies original list as well)
println list.sort { it.id }

// Sort descending (modifies original list as well)
println list.sort { -it.id }

// Sort ascending (don't modify original)
println list.sort( false ) { it.id }

// Sort descending (don't modify original)
println list.sort( false ) { -it.id }
like image 189
tim_yates Avatar answered Oct 21 '22 18:10

tim_yates