Groovy: List Operations April 21st, 2010

Anybody who has programmed in Java for sometime would attest to how frustrated they could get while operating on the Collection API. Even simple operations demand unnecessary lines of code increasing the LOC and reducing expressiveness of the intended logic. Fortunately, Java has noticed the pain and has been adding utility classes to the Collections API to improve readability of the code since Java 5. Even better, there are a couple of libraries, Lambdaj and op4j, that implement the powerful Fluent interface that takes readability to the next higher plane.

Libraries and utilities are good for Java, but we are still bound by the constraints of the language itself. Isn’t it? That is where Groovy steps in. Groovy is in a totally different league when it comes to expressiveness of code. It was designed with the “Principle of least surprise” in mind. Best of all, Groovy source compiles to java byte-code thereby only adding a jar file as a dependency to your projects.

To whet your appetite, here are a few code snippets for list operations in Groovy that will make you smile…

Create lists in groovy: Keeping the literal notation the same, you can define different implementations of the collections framework

// Returns an ArrayList by default
def personalities = ["Steve", "Bill", "Larry"]

// Returns a LinkedList
def personalities = ["Steve", "Bill", "Larry"] as LinkedList

// Returns a String array
def personalities = ["Steve", "Bill", "Larry"] as String[]

Basic list operations: There are many more operations. But this gives you a feel for how easy it is to add, remove and retrieve elements off of the list

// Defines a list of strings
def personalities = ["Steve", "Bill", "Larry"]

// Retrieving an element
assert "Larry" == personalities[2]

// Retrieving a range of elements
assert ["Bill", "Larry"] == personalities [1..2]

// Adding an element
assert ["Steve","Bill","Larry","Scott"] == (personalities<<"Scott")

// Removing an element
assert ["Steve", "Bill", "Larry"] == (personalities -= ["Scott"])

Other cool operations: These are some operations that you typically don't find in Java. Correct usage of these operations will lead you towards strong and idiomatic Groovy programming.

// Transforming one list into another
assert [2,4,6] == [1,2,3].collect{ it*2 }

// Finding every element matching the closure
assert [1,3] == [1,2,3].findAll{ it % 2 == 1 }

// Print each element of the list
[1,2,3].each{ println it }

// Spread Dot operator operates on every element of the list
assert [1,2,3] == ["a", "bb", "ccc"]*.size()   

// Spread operator is used to pass a list as method parameters
def add(a, b, c) { return a+b+c }
assert 6 == add(*[1,2,3])

There are many many more features that support the Collections framework. To list it all is not the intention of this post, rather this post is intended to give a quick feel for how easy it is to write Groovy code when dealing with a Collection of objects.

11 Responses to “Groovy: List Operations”

  1. 1. asdasd on September 4th, 2010 at 1:08 pm

    The fonts used in code parts in your website are not pleasing to the eye.

  2. 2. Agus on September 19th, 2010 at 4:54 pm

    Yes, Java is too low level and I hate populating my code with all those mind-bogging collection loops.

    What do you think of Scala?

  3. 3. Agus on September 19th, 2010 at 5:01 pm

    By the way,

    Thanks for the links to the Lambdaj and op4j libraries. I didn’t know them; they look pretty cool.

  4. 4. Ganeshji Marwaha on September 19th, 2010 at 5:58 pm

    @Agus: Scala is a wonderful language in its own space. It is statically typed, its own set of innovations and real nice mix of functional programming as well.

    I love Scala myself, but when it comes to introducing a new language to a team of existing Java developers you cannot beat groovy. It is so close to Java that developers are comfortable with it starting from day one. I am not saying they start writing idiomatic groovy from the get go, but at least they are motivated to give the new language a try. Groovy’s amazing features takes it from there.

  5. 5. forex on October 16th, 2010 at 7:55 pm

    Yes, Java is too low level and I hate populating my code with all those mind-bogging collection loops.

  6. 6. forex hedging strategy on October 17th, 2010 at 12:04 pm

    By the way,

    Thanks for the links to the Lambdaj and op4j libraries. I didn’t know them; they look pretty cool.

  7. 7. Online Dizi Film on November 30th, 2010 at 10:51 pm

    hmm java is very important. forex says to really. thanks for share

  8. 8. Craigslist New Orleans on December 25th, 2010 at 7:22 am

    Thanks for providing Groovy list operation basic list operation and other list operation are really very great this is very helpful for me i found very great stuff.

  9. 9. oil mill on March 22nd, 2011 at 1:43 am
  10. 10. binturlu on August 13th, 2011 at 10:49 am

    Good post.Thanks for the links to the Lambdaj and op4j libraries. I didn’t know them; they look pretty cool.great web site şöminemp3bilgisayar

  11. 11. jordan 11 cool grey on February 2nd, 2012 at 9:04 am

    Jordan Brand officially launched air max for sale. A new pair of Air Jordan basketball shoes today 2011 not only remains are the most representative of shoes.

Leave a Reply