Files
thpeetz-notes/Quellen/IT/Sorting List in Groovy Language.md
T

1.2 KiB

title, tags
title tags
Sorting List in Groovy Language
IT/Development/Groovy

While writing my code in groovy scripting language, I encountered a problem on how to sort a list or an array of objects. As a newbie in groovy, I was eager to look for simpler groovy way to sort a list and was so surprise when I read a blog article. I learned a very easy and readable way of sorting.

Sort Numbers

def numberList = [4,2,5,3,1]
assert [1,2,3,4,5] = numberList.sort()

Sort Letters

def alphaList = [c,d,a,b,e]
assert [a,b,c,d,e] = alphaList.sort()

Sort Object by its Field

// Create a object under file name Student.groovy
class Student{
    int id
    String fullName
}
 
//Explanation
def studentList = [ new Student(id: 2, name: Beta),
            new Student(id: 1, name: Charley),
            new Student(id: 3, name: Alpha)
          ]
 
//output will be Charley, Beta, Alpha
studentList.sort{ it.id }
 
//output will be Alpha, Beta, Charley
studentList.sort{ it.name }

Take note of the use of the sort closure sort {} verses the sort() method.As of now, I am not sure how that works but as long as it solves my problem and test is working. I am good!