Ezhil
Ezhil

Reputation: 59

How to sort multi valued list in groovy?

I have list with below values

[
[Invoice Number:452170, Date:12-05-2016, Price:124589.0, Customer Name:David Copperfield], 
[Invoice Number:452171, Date:13-04-2014, Price:453212.0, Customer Name:David Bowie], 
[Invoice Number:452172, Date:24-07-2013, Price:21458.0, Customer Name:David Beckham], 
[Invoice Number:452173, Date:21-05-2017, Price:47852.0, Customer Name:David Koresh]
]

I would like to sort this list descending order of price and then by the customer name in alphabetical order in groovy.

Upvotes: 2

Views: 1614

Answers (2)

yeugeniuss
yeugeniuss

Reputation: 180

What if you do straightforward sort?

invoices.sort { a, b ->
    if (a.Price > b.Price) return -1
    if (a.Price < b.Price) return 1
    else
        return (a.'Customer Name' > b.'CustomerName') ? -1 : 1
}

Upvotes: 1

Mene
Mene

Reputation: 3799

You can use a custom sort order by passing a closure to the sort method as described here: TO THE NEW - Groovier way of sorting over multiple fields in a list of maps in groovy

list.sort { a,b ->
   a.price <=> b.price ?: a.lastName <=> b.lastName
}

The "spaceship operator" (<=>) calls the compareTo method which is used for sorting. It returns 0 when both compared items are equal. This is where the elvis operator (?:) comes in: it evaluates the expression before it as boolean (according to groovy truthyness) and returns it's value if it is true. Since 0 evaluates to false, the expression behind the elvis operator is returned.

So if the price is not equal (a.price <=> b.price is not 0) the result of a.price <=> b.price is used for sorting. But if they are equal a.lastName <=> b.lastName is used for sorting.

Upvotes: 3

Related Questions