Sunday, February 5, 2017
Groovy Sort List
Groovy Sort List
I am posting a simple example on how to sort a list in groovy because the examples google knows about arent what I was looking for. With some deep digging I was able to find a clue that eventually solved my problem.
Its real easy to sort a list of numbers
assert [1,2,3,4] == [3,4,2,1].sort()
Or even strings
assert [Chad,James,Travis] == [James,Travis,Chad].sort()
But this was my example
class Person {
String id
String name
}
def list = [new Person(id: 1, name: James),new Person(id: 2, name: Travis), new Person(id: 3, name: Chad)]list.sort() returns James, Travis, Chad
The solution is ridiculously simple (not that I thought the previous sort would work; I have to be realistic; groovy cant do everything for me).
list.sort{it.name} will produce an order of Chad, James, Travis.
In the previous example note the use of the sort closure sort {} verses the sort() method.
Now I am not sure, off the top of my head and without a Groovy book handy, the simplest way to sort case insensitive.
assert [a1,A1] == [A1,a1].sort{fancy closure}
Available link for download