Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Groovy for Java Developers

Groovy for Java Developers – essentials

In this tutorial you will learn the most common features of Groovy that will allow you to get up and running in just a few minutes!

Basic syntax

Basically you can start with writing Java code inside Groovy, but here are some things that can simplify your code and life.

Optional semicolons

Semicolons ; are totally optional and very rarely used, so instead of this Java version:

package com.farenda.tutorials;

import java.time.Clock;


You can write:

package com.farenda.tutorials

import java.time.Clock


Optional “.class”

The same is with “.class” static, which is very often used in tests:


Prints the same:


Casting types

The as keyword is used to cast types in Groovy:

def numbers = [1, 2, 3]
println("Type: ${}")

def casted = numbers as Set
println("Type: ${}")

Gives the following results:

Type: java.util.ArrayList
Type: java.util.LinkedHashSet

Default imports

By default Groovy imports the following packages and classes:

  • java.lang
  • java.util
  • groovy.lang
  • groovy.util
  • java.math.BigInteger
  • java.math.BigDecimal

Aliases in imports

When you need to import two classes that have the same name you can create an alias to prevent conflicts. Or it can be used to shorten name of some very long class name (sometimes generated classes have such names). Example:

// aliases with shorter names:
import javax.xml.parsers.DocumentBuilder as DocBuilder
import javax.xml.parsers.DocumentBuilderFactory as DocFactory

// ... then in code:
def factory = DocFactory.newInstance()
DocBuilder db = factory.newDocumentBuilder()


Groovy has three kinds of strings:

// Simple string are within apostrophes '':
def simpleString = 'String'
println('Like in Java: ' + simpleString)

// GString are within quotes "":
println("GStrings can access vars: ${simpleString.toUpperCase()}")

// Multiline are within triple ':
def longString = '''Multiline

Note that the indentation in multiline string is preserved!

The above code produces the following text:

Like in Java: String
GStrings can access vars: STRING

Groovy Collections

Very nice feature of Groovy is a bunch of literals for creating lists, sets, and maps – especially useful in tests.

Groovy Lists

def numbers = [1, 2, 3]
println("first: ${numbers.first()}")
println("at 0: ${numbers[0]}")
println("at 1: ${numbers[1]}")
println("1st and 2nd: ${numbers[0, 1]}")
println("from 1st to 3nd: ${numbers[0..2]}")

The above code produces the following:

first: 1
at 0: 1
at 1: 2
1st and 2nd: [1, 2]
from 1st to 3nd: [1, 2, 3]

Adding and removing to a list:


numbers += 5

numbers += [6, 7]

numbers << 8 << 9

// remove range of numbers:
numbers -= (4..8)


[1, 2, 3, 4]
[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 9]

Groovy Sets

Sets can be created in very similar way to lists:

// range of numbers as set:
Set numbers = (1..10)
println("type: ${}")
println("set content: ${numbers}")

def letters = ['a', 'b', 'c'] as Set
println("type: ${}")
println("set content: ${letters}")


type: java.util.LinkedHashSet
set content: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
type: java.util.LinkedHashSet
set content: [a, b, c]

Groovy Maps

def player = 'baz'
// [string, quotes may be omitted, name from var]:
def points = ['foo': 1, bar: 2, (player): 3]

points.put('baz', 33)

points['foo'] = 11
println("foo has ${} ponits")

Note that when map key is a string quotes can be omitted! So to use a variable (here player) as a map key we have to surround it with brackets.

The above code produces:

[foo:1, bar:2, baz:3]
[foo:1, bar:2, baz:33]
foo has 11 ponits

Useful functions

def words = ['Some', 'random', 'string', 'for', 'processing']

// 'it' is default name of processed element:
def sizes = words.collectEntries {[(it.toLowerCase()): it.size()]}
println("sizes: ${sizes}")

def shorts = words
        .findAll { it.size() <= 4 }
        .collect { word -> word.toLowerCase() }
println('short words: ' + shorts)

println('has proc? ' + words.any { it.contains('proc')})
println('how many? ' + words.count { it.contains('proc')})

The output is:

sizes: [some:4, random:6, string:6, for:3, processing:10]
short words: [for, some]
has proc? true
how many? 1

It’s just the beginning

Groovy has many, many more features than presented in this introductory tutorial, but at least it should help you to start right away! :-)

If you would like to learn more about Groovy language I recommend you to read Groovy in Action 2nd Edition. It is a great book covering Groovy language in depth!


Share with the World!