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

My HSQLDB schema inspection story

This is a simple story of my need to inspect the schema of an HSQLDB database for a participar FOREIGN KEY, and the interesting things I had to do to actually inspect it. I am using an HSQLDB 1.8 database in one of my web applications. The application has been developed using the Play framework , which by default uses JPA and Hibernate . A few days back, I wanted to inspect the schema which Hibernate had created for one of my model objects. I started the HSQLDB database on my local machine, and then started the database manager with the following command java -cp ./hsqldb-1.8.0.7.jar org.hsqldb.util.DatabaseManagerSwing When I tried the view the schema of my table, it showed me the columns and column types on that table, but it did not show me columns were FOREIGN KEYs. Image 1: Table schema as shown by HSQLDB's database manager I decided to search on StackOverflow and find out how I could view the full schema of the table in question. I got a few hints, and they all pointed to

Fuctional Programming Principles in Scala - Getting Started

Sometime back I registered for the Functional Programming Principles in Scala , on Coursera. I have been meaning to learn Scala from a while, but have been putting it on the back burner because of other commitments. But  when I saw this course being offered by Martin Odersky, on Coursera , I just had to enroll in it. This course is a 7 week course. I will blog my learning experience and notes here for the next seven weeks (well actually six, since the course started on Sept 18th). The first step was to install the required tools: JDK - Since this is my work machine, I already have a couple of JDK's installed SBT - SBT is the Scala Build Tool. Even though I have not looked into it in detail, it seems like a replacement for Maven. I am sure we will use it for several things, however upto now I only know about two uses for it - to submit assignments (which must be a feature added by the course team), and to start the Scala console. Installed sbt from here , and added the path

Five Reasons Why Your Product Needs an Awesome User Guide

Photo Credit: Peter Merholz ( Creative Commons 2.0 SA License ) A user guide is essentially a book-length document containing instructions for installing, using or troubleshooting a hardware or software product. A user guide can be very brief - for example, only 10 or 20 pages or it can be a full-length book of 200 pages or more. -- prismnet.com As engineers, we give a lot of importance to product design, architecture, code quality, and UX. However, when it comes to the user manual, we often only manage to pay lip service. This is not good. A usable manual is as important as usable software because it is the first line of help for the user and the first line of customer service for the organization. Any organization that prides itself on great customer service must have an awesome user manual for the product. In the spirit of listicles - here are at least five reasons why you should have an awesome user manual! Enhance User Satisfaction In my fourteen years as a