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

Planning a User Guide - Part 3/5 - Co-ordinate the Team

Photo by  Helloquence  on  Unsplash This is the third post in a series of five posts on how to plan a user guide. In the first post , I wrote about how to conduct an audience analysis and the second post discussed how to define the overall scope of the manual. Once the overall scope of the user guide is defined, the next step is to coordinate the team that will work on creating the manual. A typical team will consist of the following roles. Many of these roles will be fulfilled by freelancers since they are one-off or intermittent work engagements. At the end of the article, I have provided a list of websites where you can find good freelancers. Creative Artist You'll need to work with a creative artist to design the cover page and any other images for the user guide. Most small to mid-sized companies don't have a dedicated creative artist on their rolls. But that's not a problem. There are several freelancing websites where you can work with great creative ar

Inheritance vs. composition depending on how much is same and how much differs

I am reading the excellent Django book right now. In the 4th chapter on Django templates , there is an example of includes and inheritance in Django templates. Without going into details about Django templates, the include is very similar to composition where we can include the text of another template for evaluation. Inheritance in Django templates works in a way similar to object inheritance. Django templates can specify certain blocks which can be redefined in subtemplates. The subtemplates use the rest of the parent template as is. Now we have all learned that inheritance is used when we have a is-a relationship between classes, and composition is used when we have a contains-a relationship. This is absolutely right, but while reading about Django templates, I just realized another pattern in these relationships. This is really simple and perhaps many of you may have already have had this insight... We use inheritance when we want to allow reuse of the bulk of one object in other

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 (insuranc