---
title: Sorting List in Groovy Language
updated: 2019-02-26 12:17:53Z
created: 2019-02-26 12:16:19Z
tags:
  - 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

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


## Sort Letters

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


## Sort Object by its Field

```groovy
// 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!