Skip to main content

Groovy Lists

In a previous post I talked about Groovy numbers. In this post we discuss Lists in Groovy. One thing that strikes me is the use of operators in Groovy. Groovy has reduced verbosity wherever possible with the use of operators.

We create a List in Java like this:
List list = new ArrayList();

and in Groovy like this:
def list = []

Why do you think we do not use generics in Groovy? You can reply on Twitter.

Groovy allows us to apply several operators like +, -, *, and <<


//Lets create an empty list. Notice, we can create a list with the []
//operator
def aList = []
//size is also an attribute in Lists (we cannot invoke methods
//without the ())
println 'size if aList is: ' + aList.size
println 'Lists created with the [] operator are of type: ' +
aList.class.getName()

//What if I want a linked list?
def lList = [] as LinkedList
println 'lList is of type: ' + lList.class.getName()

//We can also create a LinkedList by specifically instantiating it
//like in Java
def aLinkedList = new LinkedList()
println 'We just created a list of type: ' +
aLinkedList.class.getName()

//Now we are really pushing it
def wtfList = [] as String
println 'wtfList is of type: ' + wtfList.class.getName()

//We can add elements to a list using the << operator
aList << 'element 1' << new Date()
aLinkedList << 1

//We can also add elements to a List with push() and add()
aList.push(2)
aList.add("hello")
println aList
println aLinkedList

//We can instantiate and populate a List together
def aList1 = ['a', 1, new Date(), null]
println aList1
println 'size of aList1 is: ' + aList1.size()

//We can remove elements from a List with the pop() method
println 'Removing elements from aList1 using the pop() method'
println aList1.pop()
println aList1.pop()
println 'after 2 pops the size of aList1 is: ' + aList1.size()

//Lists support negative indexes where -1 is the last element
//Notice how we have accessed a List element with the [] operator
println 'aList[-1] = ' + aList[-1]
println 'aList[0] = ' + aList[0]

//Sublists can be accesed by giving a range in the subscript
//operator
println 'aList[-1..-3] = ' + aList[-1..-3]
println 'aList[-1,-3] = ' + aList[-1,-3]
println 'aList[0..3] = ' + aList[0..3]

//empty list and Groovy truth
def emptyList = []
println 'Groovy truth for empty List is: ' +
(emptyList ? true : false)
println 'Groovy truth for non empty list is: ' +
(aList ? true : false)

//Sorting
def unsortedList = [3, 4, 2, 8, 5, 7]
println unsortedList
println 'sorting...'
println unsortedList.sort()
//The sort() method also takes a closure
unsortedList = [3, 4, 2, 8, 5, 7, 10, 19, 67, 3]
println 'sorting with a closure'
unsortedList.sort {it1, it2 ->
println """${it1} <=> ${it2} """;
it1 <=> it2}

//Let's understand the <=> spaceship (compareto) operator
println 'Let us understand the <=> operator'
println '1 compareto 1 = ' + (1 <=> 1)
println '1 compareto 2 = ' + (1 <=> 2)
println '2 compareto 1 = ' + (2 <=> 1)

//we can sum lists
println "SUM(unsortedList) = " + unsortedList.sum()

//can we sum lists which have non number members?
unsortedList << "string"
println "SUM(unsortedList) = " + unsortedList.sum()

//OK now let's remove the 'string' from this list
unsortedList -= 'string'
println "unsortedList after removing 'string': " +
unsortedList

//we can also multiply lists
def listOfGames = ['football', 'cricket', 'tennis']
println listOfGames * 2

//We can also append to a list
println "Appending lists with the << operator: " +
[1,2,3] << [4,5]

//iterating lists
println "iterating a list with the each method"
unsortedList.each(){
print it + " "
}


Output from running this code:


size if aList is: 0
Lists created with the [] operator are of type: java.util.ArrayList
lList is of type: java.util.LinkedList
We just created a list of type: java.util.LinkedList
wtfList is of type: java.lang.String
["element 1", Tue Mar 17 22:13:14 IST 2009, 2, "hello"]
[1]
["a", 1, Tue Mar 17 22:13:14 IST 2009, null]
size of aList1 is: 4
Removing elements from aList1 using the pop() method
null
Tue Mar 17 22:13:14 IST 2009
after 2 pops the size of aList1 is: 2
aList[-1] = hello
aList[0] = element 1
aList[-1..-3] = ["hello", 2, Tue Mar 17 22:13:14 IST 2009]
aList[-1,-3] = ["hello", Tue Mar 17 22:13:14 IST 2009]
aList[0..3] = ["element 1", Tue Mar 17 22:13:14 IST 2009, 2, "hello"]
Groovy truth for empty List is: false
Groovy truth for non empty list is: true
[3, 4, 2, 8, 5, 7]
sorting...
[2, 3, 4, 5, 7, 8]
sorting with a closure
3 <=> 4
4 <=> 2
3 <=> 2
4 <=> 8
8 <=> 5
4 <=> 5
7 <=> 10
10 <=> 19
19 <=> 67
67 <=> 3
19 <=> 3
10 <=> 3
7 <=> 3
8 <=> 3
2 <=> 3
3 <=> 3
4 <=> 3
4 <=> 7
5 <=> 7
8 <=> 7
8 <=> 10
Let us understand the <=> operator
1 compareto 1 = 0
1 compareto 2 = -1
2 compareto 1 = 1
SUM(unsortedList) = 128
SUM(unsortedList) = 128string
unsortedList after removing 'string': [2, 3, 3, 4, 5, 7, 8, 10, 19, 67]
["football", "cricket", "tennis", "football", "cricket", "tennis"]
Appending lists with the << operator: [1, 2, 3][4, 5]
iterating a list with the each method
2 3 3 4 5 7 8 10 19 67

Comments

Popular posts from this blog

Running your own one person company

Recently there was a post on PuneTech on mom's re-entering the IT work force after a break. Two of the biggest concerns mentioned were : Coping with vast advances (changes) in the IT landscape Balancing work and family responsibilities Since I have been running a one person company for a good amount of time, I suggested that as an option. In this post I will discuss various aspects of running a one person company. Advantages: You have full control of your time. You can choose to spend as much or as little time as you would like. There is also a good chance that you will be able to decide when you want to spend that time. You get to work on something that you enjoy doing. Tremendous work satisfaction. You have the option of working from home. Disadvantages: It can take a little while for the work to get set, so you may not be able to see revenues for some time. It takes a huge amount of discipline to work without a boss, and without deadlines. You will not get the benefits (insuran

Testing Groovy domain classes

If you are trying to test Grails domain class constraints by putting your unit test cases in the 'test/unit' directory, then your tests will fail because the domain objects will not have the 'valdate' method. This can be resolved in two ways: Place the test cases inside test/integration (which will slow things down) Use the method 'mockForConstraintsTests(Trail)' to create mock method in your domain class and continue writing your test cases in 'test/unit' What follows is some example code around this finding. I am working on a Groovy on Grails project for a website to help programmers keep up and refresh their skills. I started with some domain classes and then moved on to write some unit tests. When we create a Grails project using grails create-app , it creates several directories, one of which is a directory called 'test' for holding unit tests. This directory contains two directories, 'unit', and 'integration' for uni

Some thoughts on redesigning education

Some time back I read a blog post on redesigning education. It asked some very good questions. Stuff which I had been thinking of myself. I left my thoughts on the blog, but I would also like to start a conversation around these ideas with those who read this blog as well. I would like to know what other people think of the issue of redesigning (college) education. I have often thought about how college education can be improved. To answer this question, we first have to ask a very basic question. What is the purpose of education? To me, we need education for 3 things: To learn more about the world around us To lead positive constructive lives To earn a good living / fulfill our ambitions I think education has to a large extent evolved to fulfill #3 (with a bias towards earning a comfortable living). The semester system, along with multiple choice tests, and grading, has made our education system into an assembly line. Students are pushed into the assembly line, given classes, admini