Parse a date

Groovy’s Date class has a built in parse() method. To parse a date from a string you just need to supply the date format and the date string.

Date date = Date.parse("dd-MM-yyyy","31-12-2010")
String out = date.format("MM-dd-yyyy")
 
assert out == "12-31-2010"

The date format is specified using identifiers from java.text.SimpleDateFormat

Find the last day of a month

The Calendar class has a getActualMaximum() method that we can use to find the last day of a month.

Calendar calendar = GregorianCalendar.instance
calendar.set(2010,3,1) // 1st April 2010
 
def lastDay = calendar.getActualMaximum(GregorianCalendar.DAY_OF_MONTH)
assert lastDay == 30

Zero pad a number

You can zero pad a number with the String.format() method.

For example, suppose you want to zero pad the a number to 5 characters:

def num = 123
def numPadded = String.format("%05d", num)
assert numPadded == '00123'

If you want to pad using spaces you would use a format string: %5d

If you want to pad using zeros then add a zero after the percent: %05d

Append two lists

Lists are appended using Java’s addAll() method:

def listA = [1,2,3]
def listB = [4,5,6]
 
listA.addAll(listB)
 
assert listA == [1,2,3,4,5,6]

Test if a string is an integer

Groovy provides a string function isInteger() that tests if a string is an integer:

def num1 = "12345"
def num2 = "123.45"
assert num1.isInteger()
assert !num2.isInteger()

Check if a list contains a value

A Groovy list is a Java ArrayList which provides a contains() method.

def list = [1,3,5]
assert list.contains(3)
assert !list.contains(4)

Alternatively you can use Groovy’s in operator.

def list = [1,3,5]
assert 3 in list
assert !(4 in list)

Note that this method may provide unexpected results when comparing Strings and GStrings. For example, the String “1″ and the GString “1″ are not considered to be equal.

def one = 1
​​def list = ["1","2","3"]
 
// These are false
assert list.contains( "${one}" )
assert "${one}" in list
 
// These are true
assert list.contains( "1" )
assert "1" in list
 
// Convert GStrings to Strings so these are also true
assert list.contains( "${one}".toString() )
assert "${one}".toString() in list

Get the hash of a string

You can get a quick hash code for a string (and all other objects) in Groovy by simply calling it’s hashCode() method.

def message = 'hello'
println message.hashCode()

Which prints

99162322

Use a mixin

Groovy provides a mixin method for creating mixin classes.

// Create a simple class
class Person {
    def first
    def last
}
 
// Create the mixin class
class PersonMixin {
    def getFullName() {
        "${first} ${last}"
    }
}
 
// Apply the mixin
Person.mixin PersonMixin
 
def person = new Person(first:'Hugh',last:'Jackman')
 
assert 'Hugh' == person.first
assert 'Jackman' == person.last
assert 'Hugh Jackman' == person.fullName

Test if a map contains a key

Groovy maps have a containsKey() method for testing if a map contains a given key.

map = [name:'Kraken',size:'Huge']
 
assert map.containsKey('size')
assert !map.containsKey('birthDate')

Dynamically add properties to a class

To dynamically add properties to a class we use metaClass.getProperty.

For example, to add a percentage property to our numbers.

Number.metaClass.getProperty = { propertyName ->
    if (propertyName == 'percent') { delegate / 100 }
    else { delegate }
}
 
assert 20.5.percent== 0.205
assert 20.percent == 0.2

Important: If you add a dynamic property to one of your classes and you want that property to be available in any subclasses you create then you must call ExpandoMetaClass.enableGlobally() before your application starts such as in the main method or servlet bootstrap.