Over a million developers have joined DZone.

Productive Programming in Groovy

DZone's Guide to

Productive Programming in Groovy

· DevOps Zone
Free Resource

The Nexus Suite is uniquely architected for a DevOps native world and creates value early in the development pipeline, provides precise contextual controls at every phase, and accelerates DevOps innovation with automation you can trust. Read how in this ebook.

The only thing constant in this world is change! In the 1990s, Java shook up the computing world by bringing managed runtime (virtual machines) to mainstream programming. Today, there are many new languages emerging to replace languages that are popular today. For JavaScript, some attempting to replace them are TypeScript (Microsoft) and Dart (Google). For C/C++, attempts to replace them include D language and Go (Google). Interestingly, for Java, the main competition comes from languages that are built on top of the Java environment itself! 

Did you know that there are more than 200 languages that target the Java platform? Languages like Scala, Clojure, Groovy, JRuby, and Jython are few but important languages that target the Java platform. Of these, of interest to us is Groovy since it is getting wide attention and gaining steady popularity in the last few years.

Why Choose Groovy? 

I  started working in Groovy entirely by chance. I was trying to write code for my pet project and realized that Java was slowing me down. I explored using alternative languages, but couldn’t. Why? There are many reasons, which will be of interest to you as well when you try to start using Groovy, so I’ll discuss them in detail here. My comparison is mainly with Python and Ruby since they were the popular alternative languages I considered. 

First, I had considerable experience programming in Java and in using the Java libraries and framework. When I move to languages like Python or Ruby, I have to leave my familiar land and learn the language and the eco-system. Java’s main advantage is the vast set of libraries and frameworks (most of them free and open source) and I am likely to lose them with such a move. I considered using Jython and JRuby - but I preferred Groovy because I could seamlessly switch back and forth between Java and Groovy (since Groovy is more or less a superset Java). 

Second, I had little spare time to spend learning a new language from scratch. Groovy has Java-like syntax and hence the learning curve is not steep. Once I installed Groovy, I could straightaway start programming in Groovy since I code mostly in Java and gradually move on to more “Groovyish” code. 

Third, I had to consider deployment aspects as well. Though Python and Ruby are also installed in a millions of machines, Java runtime is ubiquitous. That meant I could just ship Groovy jar file along with my application and get the program working in any machine. 

In short, moving from Java to Groovy was like shifting my home from India to Australia - it is a familiar terrain but still I need to know many things to survive there. For me, moving from Java to Ruby or Python is like moving from India to Antartica - it is a completely different terrain - yes, I am game for adventure, but not now when I have immediate work to get done!  

I will confess the fourth reason that is non-technical: I liked Venkat Subramaniam’s excellent book on Groovy [2] and his presentations on Groovy. Being a like-minded geek, I decided to try, learn, and start using Groovy.

What is Groovy? 

Groovy is a dynamic language that dynamically compiles the code to the Java platform. It is popular as a scripting language and also widely used for unit testing Java code. Groovy is open source (Apache v2 license) and is backed by VMware. James Strachan conceived the idea of Groovy language and started development in 2003. The current (as on November 2013) stable release is 2.1. You can use Groovy in most common operating systems - Linux, Windows, and Mac. 

Groovy is also reasonably popular. It made headlines when Groovy entered the top 20 list in the widely cited TIOBE language popularity index in October 2013 (it was in 53rd position in 2012!). There were 1.7 million Groovy downloads in 2012. We need to take these figures (especially on popularity) with a pinch of salt; nevertheless, it is safe to say that Groovy is gaining steady popularity in the last few years.  

Can you Show How Groovy is “Better Java”?

Hello World Example

Let’s start with the classic “hello world” example: 

class Hello {
	public static void main(String []args) {
		System.out.println("hello world");

The code that is marked strikethrough is to show that those parts of the Java code is not need in Groovy - this simple and sweet println will do:   

println("hello world")

First (Simple) Example 

How about writing code for implementing the “type” command (or the “cat” command) but that is limited to printing the file names passed as argument? Here is the Java version:

import java.io.*;

class Type {
	public static void main(String []files) {
		// process each file passed as argument 
		for(String file : files) {
			// try opening the file with FileReader 
			try (FileReader inputFile = new FileReader(file)) { 
				int ch = 0; 
				while( (ch = inputFile.read()) != -1) {
					// ch is of type int - convert it back to char
					System.out.print( (char)ch ); 
			} catch (FileNotFoundException fnfe) {
				System.err.printf("Cannot open the given file %s ", file);
			catch(IOException ioe) {
				System.err.printf("Error when processing file %s; skipping it", file);
			// try-with-resources will automatically release FileReader object  

Now, what I don’t like about this code is it is too verbose. Also, why should I worry about low-level details like reading characters as integer, converting the integer back to character, checking with -1 to check end-of-file, etc? 

As many of you know, Java 7 introduced NIO.2 which simplified much of the file and I/O processing. With Java 7, the code looks simpler when compared to the earlier versions of Java, but still looks verbose: 

import java.nio.file.*;
import java.io.IOException;

class Type {
	public static void main(String []files) {	
		// process each file passed as argument 
		for(String file : files) {
			try {
				Files.copy(Paths.get(file), System.out);
			} catch (IOException e) {

Compare this with Groovy version which is a sweet one-liner: 

args.each { println new File(it).getText() }

Traversing a data structure is easy in Groovy - you can use “closures” instead of plain loops and use each() method as done in this case. Groovy helps you work at higher levels of abstraction (like most other scripting languages). Since file processing is a common task in scripting languages, Groovy provides a higher-level abstraction to this functionality, and hence the code is much simpler. 

Second (More Detailed) Example

Now let us take a bit more difficult task: take key-value pairs, put them in a map, sort them by value and by key and print the results. Let’s do that step-by-step. First, let’s take key-value pairs and put them in a map: 

Map<String, String> inglishWords = new HashMap<>();
inglishWords.put("Shampoo", "'Chapmo' (Hindi)"); 
inglishWords.put("Sugar", "'Sarkkarai' (Tamil)");  
inglishWords.put("Copra", "'Koppara' (Malayalam)"); 
inglishWords.put("Jute", "'Jhuto' (Bengali)"); 
inglishWords.put("Cot", "'Khatva' (Sanskrit)"); 

for(Map.Entry<String, String> word : inglishWords.entrySet()) {                        System.out.printf("%s => %s \n", word.getKey(), word.getValue());  

In this code, we have taken words such as Shampoo and Sugar in English and mapped them to their Indian origin words. Here is the Groovy equivalent:

def inglishWords =    [ "Shampoo" : "'Chapmo' (Hindi)", 
                        "Sugar" : "'Sarkkarai' (Tamil)",   
                        "Copra" : "'Koppara' (Malayalam)",  
                        "Jute" : "'Jhuto' (Bengali)",  
                        "Cot" : "'Khatva' (Sanskrit)" ]  

inglishWords.each { 
    key, value ->    
            println "$key => $value"   

In this case, Groovy provides “syntactic sugar” in the form of array-like [] syntax for the Map data structure. With each() method closure, we have named index values in the map (“key”, and “value”). As you can see you need to learn some new syntax, like how to use $ instead of %s in printf or println while printing the values; but our experience shows that you can progressively learn new syntax as you try more programs and get more sophisticated. Let us now sort the map and print the contents. Here is the Java version: 

System.out.println("The (key-based) sorted map is: ");

Map<String, String> keySortedMap = new TreeMap<>(inglishWords); 
for(Map.Entry<String, String> word : keySortedMap.entrySet()) {                     System.out.printf("%s => %s \n", word.getKey(), word.getValue());  

Here is the Groovy equivalent: 

println "The (key-based) sorted map is: " 
def keySortedMap = inglishWords.sort() 
keySortedMap.each { 
        key, value ->    
            println "$key => $value"   

But now you may have this question - “is Groovy a mere-syntactic sugar over Java?” The answer is NO - Groovy provides powerful features that helps you become more productive. This will become evident when we try our next task - sort the map by value. 

Though I am an experienced Java programmer, I found that trying to sort a map by value isn’t straight-forward, so I quickly checked stackoverflow.com for a quick solution! There were 38 answers to this question with lots of debates on each answer; this shows (a) there are quite a few programmers who try to do this, and (b) the answer is non-trivial. Here we go: 

class MapUtil {
    // this code segment from http://stackoverflow.com/questions/109383/how-to-sort-a-mapkey-value-on-the-values-in-java 
    public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue( Map<K, V> map ) {
        List<Map.Entry<K, V>> list =
            new LinkedList<Map.Entry<K, V>>( map.entrySet() );
        Collections.sort( list, new Comparator<Map.Entry<K, V>>() {
            public int compare( Map.Entry<K, V> o1, Map.Entry<K, V> o2 ) {
                return (o1.getValue()).compareTo( o2.getValue() );
        } );

        Map<K, V> result = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            result.put( entry.getKey(), entry.getValue() );
        return result;

Now the code that makes use this utility function: 

System.out.println("The (value-based) sorted map is: ");
Map<String, String> valueSortedMap = MapUtil.sortByValue(inglishWords); 
for(Map.Entry<String, String> word : valueSortedMap.entrySet()) {                  System.out.printf("%s => %s \n", word.getKey(), word.getValue());  

Now compare it with the Groovy version: 

println "The (value-based) sorted map is: " 

def valueSortedMap = inglishWords.sort { it.value }  
valueSortedMap.each { 
    key, value ->    
            println "$key => $value"   

In this case, we just passed the it.value (which stands for the current iterator’s value) to the sort method. With the power of closures, the code became easy, simple, and readable. 

Note that Java 8 introduces closures (also known as “lambda functions”) which is one of the important features of Groovy we discussed here. However, it is unlikely that Java 8 adding closures will deter languages like Groovy in gaining popularity. There are numerous other features that make Groovy attractive, for example its meta-programming capabilities that makes the language attractive for creating DSLs. 

Last (HTML and XML Generation) Example

One of the common tasks we perform as Java developers is to generate output in some structured format. Let us create simple HTML and XML files with Java and Groovy. Here is the Java version without using libraries or templates (e.g., vector templates) for generating HTML file: 

try  (PrintWriter pw = new PrintWriter(new FileWriter("./index.java.html"))) {
	pw.println("<html> <head> <title>Words from Indian origin in English</title> </head> <body>"); 
	pw.println("<h1>Words from Indian origin in English</h1>"); 
	pw.println("<table border='1'> <tr> <th>Inglish word</th> <th>Origin</th></tr>"); 

   	for(Map.Entry<String, String> word : inglishWords.entrySet()) {              		pw.printf("<tr> <td> %s </td> <td> %s </td> </tr>", word.getKey(), word.getValue());  

	pw.println("</table> <p style='font-style:italic;font-size:small;float:right'>Results obtained at " + new Date() + "</p> </body> </html>"); 

Groovy supports builders (based on Gang-of-four Builder design pattern) for creating HTML and XML files. With that, the code looks like this:

def writer = new StringWriter()
def doc = new MarkupBuilder(writer)
doc.html() {
    head {
        title("Words from Indian origin in English") 
    body {
    h1("Words from Indian origin in English")
       table(border:1) {
           tr {
                th("Inglish word")
            inglishWords.each { word, root ->
            tr {
  p(style:'font-style:italic;font-size:small;float:right', "Results obtained at ${new Date().dateTimeString}")

Unlike the earlier examples, Groovy code isn’t shorter than the Java version, but it is certainly more readable than the Java version. Both these programs generate the same HTML output:

HTML output generated from Java/Groovy

For the same output, let us create an XML output in Java:

try  (PrintWriter pw = new PrintWriter(new FileWriter("./words.xml"))) { 
	for(Map.Entry<String, String> word : inglishWords.entrySet()) {               	pw.printf("\t<language word='%s'> \n \t\t <origin> 
'%s'</origin> \n \t </language> \n", word.getKey(), word.getValue());  

It generates the following XML output: 


<language word='Sugar'> 
  <origin> ''Sarkkarai' (Tamil)'</origin> 

<language word='Copra'> 
  <origin> ''Koppara' (Malayalam)'</origin> 

<language word='Shampoo'> 
  <origin> ''Chapmo' (Hindi)'</origin> 

<language word='Jute'> 
  <origin> ''Jhuto' (Bengali)'</origin> 

<language word='Cot'> 
  <origin> ''Khatva' (Sanskrit)'</origin> 


This is the Groovy version that gets the same work done with ease:

xmlbuilder = new groovy.xml.MarkupBuilder()
xmlbuilder.inglishwords {
        words.each { 
              key, value ->
                  language(word:key) { origin(value) }

Hope this example settles your concerns in case you had any doubts on how useful Groovy can be for regular programming tasks. 

Where to Go from Here? 

We have merely scratched the surface on what you can accomplish with Groovy. We haven’t covered many topics. You are welcome to explore programming improvements (when compared to Java) such as automatic check for nulls, helper methods, embedded expressions in strings, and operator overloading. Of course, make sure to explore its meta-programming and regular expression handling capabilities. Its builders can simplify tasks such as JSON processing. If you are a serious web-developer, you’ll find Grails web framework and Groovy Server Pages (GSP) to be interesting. If you are an admin, you may find Gradle build automation framework useful.   

If you are a seasoned Java programmer and want to build on top of your existing skills, try Groovy. You will find that regular tasks such as using data-structures, creating XML/HTML output, building GUIs, are considerably easier when you use Groovy. Grails framework (that is similar to Ruby on Rails) is built on top of powerful and popular frameworks such as Spring and Hibernate; if you are a serious web-programmer then try Grails. Like other dynamic languages, Groovy is an excellent candidate for creating DSLs (Domain Specific Languages) - if you have need, you can consider using Groovy for building your next DSL.   

Bottom-line: If you use Groovy instead of Java for your regular work, you’ll surely see your productivity almost double. But a warning though - as in learning any new language or tool, there is always a initial drop in productivity when you learn the ropes; but once you become proficient, your productivity zooms. I would recommend you to move to programming in Groovy not just for productivity but for health reasons as well - I get wrist pain typing Java code, and its now gone after I started programming in Groovy. So, what are you waiting for - get groovier and have fun! 


[1] Groovy homepage: http://groovy.codehaus.org (Go to this page to download Groovy or learn more about Groovy) 

[2] “Programming Groovy 2: Dynamic Productivity for the Java Developer”, Venkat Subramaniam, Pragmatic Bookshelf, 2013. (If you want to learn Groovy’s latest version, this is the best book to start with) 

[3] "Groovy in Action", Dierk Koenig, Andrew Glover, Paul King, Guillaume Laforge, Jon Skeet, Manning Publications, 2007. (Early books that made Groovy popular and the definitive reference to the language; second edition covering Groovy 2 features is set to be released in 2014). 

[4] “Groovy for Domain-Specific Languages”, Fergal Dearle, Packt, 2010. (If you plan to develop DSLs using Groovy, this is an excellent resource to get started). 

[5] “The Definitive Guide to Grails 2”, Jeff Scott Brown, Graeme Rocher, Apress, 2013. (This is a recent book on the latest version of Grails framework).

The DevOps Zone is brought to you in partnership with Sonatype Nexus.  See how the Nexus platform infuses precise open source component intelligence into the DevOps pipeline early, everywhere, and at scale. Read how in this ebook


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}