Sorting Objects By A Specific Property In Groovy

LoopedNetwork
2 min readMay 15, 2021

--

As someone who does a lot of scripting and not a ton of large-scale development work, it’s a bit rare that I make objects in my code. Outside of PowerShell, which basically makes everything an object for you, I typically spend a lot of time working with dictionaries instead. Occasionally, though, objects are far more useful for me so that I can more easily create parent-child relationships or use an object as a property of another object. Anyone who has ever tried working with lists of dictionaries or nested dictionaries would likely agree.

Recently, I created a few objects for a script I was putting together, and I needed to sort a list of them. One of the properties of the object was a date, and that’s what I wanted to sort them by. Using the .sort() method in Groovy will attempt to automatically sort the objects for you. However, it may not be the value you want, and in my case the objects were sorted by their first property, an ID number, rather than the date.

I took to DuckDuckGo, and after a quick search I discovered that I could use the following syntax to specify the property to sort on:

myList.sort{ it.date }

In this case, date is the property that I want to sort on. Just note that curly braces are used rather than the parentheses that would normally be used with the sort method. Here's a fully fleshed out example where I want to sort my objects by the name property rather than the id property that is used by default.

Here I instantiate two objects called first and second, followed by placing them into a list named myList. I first print the id of each object to show the default ordering. Then I sort the objects by their name property and print the id values again to show that the order has changed.

It’s also worth noting that this will sort the objects from largest to smallest, hence why 1 comes before 2 and why “Hello” comes before “World.” If I needed them to be sorted in the opposite order, I could take the results and call the .reverse() method on them.

Originally published at https://looped.network on May 15, 2021.

--

--

LoopedNetwork
LoopedNetwork

Responses (1)