Flag This Hub

Sorting List in Groovy Language

By


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!

Hope the above code helps you. For your suggestions and tips, please send me an email or leave your comment below.

Comments

Paul 2 years ago

What if the field in your object is a java.util.Date field. What type of sorting will it use?

innovator 21 months ago

http://jlorenzen.blogspot.com/2008/05/groovy-sort-

Look at this:

assert ['a1', 'A2', 'a3'] == ['A2','a3', 'a1'].sort { a, b -> a.compareToIgnoreCase b }

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Like this Hub?
    Please wait working