TestingCodes
TestingCodes

Reputation: 127

Sort Array of Object in groovy

I have an Array of Object that is declared and look like this:

def meal = [['Apple','Tomatoes', 'Coffee'],['Peach','Broccoli', 'Water'],['Orange','Peas', 'Pepsi'],['Banana','Beans', 'Coffee']]

I need to sort these objects based on the third element of each object and then based on the second element. So my output would be:

meal = [['Banana','Beans', 'Coffee'], ['Apple','Tomatoes', 'Coffee'],['Orange','Peas', 'Pepsi'],['Peach','Broccoli', 'Water'],]

Upvotes: 0

Views: 1629

Answers (2)

tim_yates
tim_yates

Reputation: 171094

You can just do this

meal.sort { a, b -> a[2] <=> b[2] ?: a[1] <=> b[1] }

When the two are equal, a[2] <=> b[2] is 0, so it runs the second half

Upvotes: 4

Asela Pathirage
Asela Pathirage

Reputation: 85

First of all, iterate through the desired sorting in reverse order. Hope the following code will help you.

def list = [['Apple','Tomatoes', 'Coffee'],['Peach','Broccoli', 'Water'],['Orange','Peas', 'Pepsi'],['Banana','Beans', 'Coffee']];

list = list.sort{ a,b -> a[1] <=> b[1] }
list = list.sort{ a,b -> a[2] <=> b[2] }

println(list);

Upvotes: 1

Related Questions