Skip to content

Groovy Common Syntax

Groovy is a flexible programming language based on the Java platform, combining many powerful features from Python, Ruby, and Smalltalk. Below are some common Groovy syntaxes to help you get started quickly.

Variable Declaration

In Groovy, variables can be declared using the def keyword or by explicitly specifying a type.

groovy
// Using the def keyword
def name = "Groovy"

// Explicitly specifying a type
String greeting = "Hello, ${name}!"

Data Types

Groovy supports various data types, including integers, floating-point numbers, booleans, and strings.

groovy
def a = 10          // Integer
def b = 10.5        // Floating-point number
def c = true        // Boolean
def d = "Groovy"    // String

Logical Operations

Groovy supports logical operators such as && (logical AND), || (logical OR), and ! (logical NOT).

groovy
def a = 10
def b = 20

if (a > 0 && b > 0) {
    println "Both numbers are positive"
} else if (a > 0 || b > 0) {
    println "At least one number is positive"
} else {
    println "Both numbers are non-positive"
}

Conditional Statements

Groovy supports if-else and switch conditional statements.

groovy
def number = 10
if (number > 0) {
    println "Number is positive"
} else {
    println "Number is non-positive"
}

switch (number) {
    case 0:
        println "Number is zero"
        break
    case { it > 0 }:
        println "Number is positive"
        break
    default:
        println "Number is negative"
}

Loop Statements

Groovy supports for, while, and do-while loops.

groovy
// for loop
for (i in 0..9) {
    println i
}

// while loop
def i = 0
while (i < 10) {
    println i++
}

// do-while loop
def j = 0
do {
    println j++
} while (j < 10)

Strings

String Concatenation

In Groovy, you can use the + operator or ${} syntax for string concatenation.

groovy
def name = "Groovy"
def greeting = "Hello, " + name + "!"
println greeting  // Outputs Hello, Groovy!

def greeting2 = "Hello, ${name}!"
println greeting2  // Outputs Hello, Groovy!

String Slicing

You can use the substring method to extract a portion of a string.

groovy
def str = "Hello, Groovy!"
println str.substring(7)  // Outputs Groovy!
println str.substring(0, 5)  // Outputs Hello

String Replacement

Use the replace method to substitute parts of a string.

groovy
def str = "Hello, Groovy!"
println str.replace("Groovy", "Java")  // Outputs Hello, Java!

String Splitting

The split method splits a string into an array.

groovy
def str = "Hello, Groovy!"
def parts = str.split(", ")
println parts[0]  // Outputs Hello
println parts[1]  // Outputs Groovy!

String Splitting and Indexing

The tokenize method splits a string into a list, allowing access to specific parts via indices.

groovy
def str = "Hello, Groovy!"
println str.tokenize(",")[1]  // Outputs Groovy!

String Trimming

Use the trim method to remove whitespace from both ends of a string.

groovy
def str = "  Hello, Groovy!  "
println str.trim()  // Outputs Hello, Groovy!

String Length

Access the length of a string using the length property.

groovy
def str = "Hello, Groovy!"
println str.length()  // Outputs 14

String Containment

Check whether a string contains a substring using the contains method.

groovy
def str = "Hello, Groovy!"
println str.contains("Groovy")  // Outputs true

String Searching

Use the indexOf method to find the position of a substring within a string.

groovy
def str = "Hello, Groovy!"
println str.indexOf("Groovy")  // Outputs 7

String Comparison

Compare strings using operators like ==, !=, <, >, <=, and >=.

groovy
def str1 = "Hello, Groovy!"
def str2 = "Hello, Java!"
println str1 == str2  // Outputs false
println str1 != str2  // Outputs true
println str1 < str2  // Outputs true
println str1 > str2  // Outputs false
println str1 <= str2  // Outputs true
println str1 >= str2  // Outputs false

String Escaping

Escape special characters with \, such as \n for a newline.

groovy
def str = "Hello,\nGroovy!"
println str  // Outputs Hello,
             // Groovy!

String Templates

Groovy allows embedding variables in strings using the ${} syntax.

groovy
def name = "Groovy"
def greeting = "Hello, ${name}!"
println greeting  // Outputs Hello, Groovy!

String Regular Expression Matching

Use the ==~ operator for regular expression matching.

groovy
def emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
def str = "google@163.com"
println str ==~ emailPattern  // Outputs true

Multiline Strings

Define multiline strings using triple quotes """ or '''.

groovy
def multiLineStr = """
    This is a multi-line
    string in Groovy.
"""
println multiLineStr

Lists

Lists are a common data structure in Groovy, capable of holding elements of different types. Here are some commonly used operations on lists.

Defining Lists

Use square brackets [] to define a list.

groovy
def list = [1, 2, 3, 'Groovy', true]

Accessing List Elements

Access elements by index, starting from 0.

groovy
def list = [1, 2, 3, 'Groovy', true]
println list[3]  // Outputs Groovy

Modifying List Elements

Update elements by their index.

groovy
def list = [1, 2, 3, 'Groovy', true]
list[3] = 'Java'
println list  // Outputs [1, 2, 3, 'Java', true]

Adding Elements

Add elements using the add method or the left shift operator <<.

groovy
def list = [1, 2, 3]
list.add(4)
println list  // Outputs [1, 2, 3, 4]

list << 5
println list  // Outputs [1, 2, 3, 4, 5]

Removing Elements

Remove elements using the remove method.

groovy
def list = [1, 2, 3, 4, 5]
list.remove(0)
println list  // Outputs [2, 3, 4, 5]

List Length

Get the size of a list using the size method.

groovy
def list = [1, 2, 3, 4, 5]
println list.size()   // Outputs 5

Iterating Over Lists

Use a for loop to iterate through list elements.

groovy
def list = [1, 2, 3, 4, 5]
for (item in list) {
    println item
}

Alternatively, use the each method.

groovy
def list = [1, 2, 3, 4, 5]
list.each { println it }

List Transformations

collect: Apply a transformation to each element.

groovy
def list = [1, 2, 3, 4, 5]
def newList = list.collect { it * 2 }
println newList  // Outputs [2, 4, 6, 8, 10]

findAll: Filter elements that meet a condition.

groovy
def list = [1, 2, 3, 4, 5]
def newList = list.findAll { it % 2 == 0 }
println newList  // Outputs [2, 4]

List Matching

any: Check if any element meets a condition.

groovy
def list = [1, 2, 3, 4, 5]
println list.any { it % 2 == 0 }  // Outputs true

every: Verify all elements satisfy a condition.

groovy
def list = [1, 2, 3, 4, 5]
println list.every { it % 2 == 0 }  // Outputs false

List Slicing

Extract a sublist using the subList method.

groovy
def list = [1, 2, 3, 4, 5]
println list.subList(1, 4)  // Outputs [2, 3, 4]

Sorting Lists

Sort a list using the sort method.

groovy
def list = [3, 1, 4, 2, 5]
println list.sort()  // Outputs [1, 2, 3, 4, 5]

Reversing Lists

Reverse a list using the reverse method.

groovy
def list = [1, 2, 3, 4, 5]
println list.reverse()  // Outputs [5, 4, 3, 2, 1]

Checking for Element Presence

Use the contains method to verify if a list includes a specific element.

groovy
def list = [1, 2, 3, 4, 5]
println list.contains(3)  // Outputs true
println list.contains(6)  // Outputs false

Merging Lists

Combine two lists using the plus method or the + operator.

groovy
def list1 = [1, 2, 3]
def list2 = [4, 5, 6]
println list1.plus(list2)  // Outputs [1, 2, 3, 4, 5, 6]
println list1 + list2      // Outputs [1, 2, 3, 4, 5, 6]

Clearing Lists

Clear a list using the clear method.

groovy
def list = [1, 2, 3, 4, 5]
list.clear()
println list  // Outputs []

Maps

Maps are another common data structure in Groovy, storing key-value pairs. Here are some frequently used map operations.

Defining Maps

Define a map using square brackets [:] or curly braces {}.

groovy
def map = [:]
map = ["name": "Groovy", "version": 2.5]

Accessing Map Values

Access values by their keys.

groovy
def map = ["name": "Groovy", "version": 2.5]
println map["name"]  // Outputs Groovy

Modifying Map Values

Update values by their keys.

groovy
def map = ["name": "Groovy", "version": 2.5]
map["name"] = "Java"
println map  // Outputs [name:Java, version:2.5]

Adding Key-Value Pairs

Add new entries using the put method or direct assignment.

groovy
def map = ["name": "Groovy"]
map.put("version", 2.5)
println map  // Outputs [name:Groovy, version:2.5]

map["author"] = "James"
println map  // Outputs [name:Groovy, version:2.5, author:James]

Removing Entries

Delete entries using the remove method.

groovy
def map = ["name": "Groovy", "version": 2.5]
map.remove("version")

println map // Output [name:Groovy]


### Map Size

You can use the `size` method to get the size of a map.

```groovy
def map = ["name": "Groovy", "version": 2.5]
println map.size()  // Output 2

Iterating Over a Map

You can use the each method to iterate over key-value pairs in a map.

groovy
def map = ["name": "Groovy", "version": 2.5]
map.each { key, value ->
    println "${key}: ${value}"
}

Checking Keys or Values

You can use the containsKey and containsValue methods to check whether a map contains a specific key or value.

groovy
def map = ["name": "Groovy", "version": 2.5]
println map.containsKey("name")  // Output true
println map.containsValue(2.5)  // Output true

Clearing a Map

You can use the clear method to empty a map.

groovy
def map = ["name": "Groovy", "version": 2.5]
map.clear()
println map  // Output [:]

Merging Maps

You can use the putAll method to merge all elements from one map into another.

groovy
def map1 = ["name": "Groovy"]
def map2 = ["version": 2.5]
map1.putAll(map2)
println map1  // Output [name:Groovy, version:2.5]

Getting All Keys or Values

You can use the keySet and values methods to retrieve all keys or values from a map.

groovy
def map = ["name": "Groovy", "version": 2.5]
println map.keySet()  // Output [name, version]
println map.values()  // Output [Groovy, 2.5]

Functions

In Groovy, functions are referred to as methods and can be defined within classes or as part of scripts. Below are some common syntaxes for defining and calling Groovy functions.

Defining a Function

You can define a function using the def keyword.

groovy
def greet(name) {
    return "Hello, ${name}!"
}

Calling a Function

After defining a function, you can call it by specifying its name and arguments.

groovy
def result = greet("Groovy")
println result  // Output Hello, Groovy!

Functions with Default Parameters

You can provide default values for parameters when defining a function.

groovy
def greet(name = "World") {
    return "Hello, ${name}!"
}

println greet()        // Output Hello, World!
println greet("Groovy") // Output Hello, Groovy!

Functions with Multiple Parameters

You can define functions that accept multiple arguments.

groovy
def add(a, b) {
    return a + b
}

println add(3, 5)  // Output 8

Anonymous Functions

You can define anonymous functions and assign them to variables or pass them as arguments.

groovy
def multiply = { a, b -> a * b }
println multiply(3, 5)  // Output 15

Functions with Variable Arguments

You can define functions that accept a variable number of arguments.

groovy
def sum(... numbers) {
    def total = 0
    for (number in numbers) {
        total += number
    }
    return total
}

println sum(1, 2, 3, 4)  // Output 10

Functions with Closures

You can define functions that accept closures as arguments.

groovy
def operate(a, b, closure) {
    return closure(a, b)
}

def add = { x, y -> x + y }
println operate(3, 5, add)  // Output 8

Functions Returning Multiple Values

You can define functions that return multiple values, which will be returned as a list.

groovy
def getCoordinates() {
    return [10, 20]
}

def (x, y) = getCoordinates()
println "x: ${x}, y: ${y}"  // Output x: 10, y: 20

Recursive Functions

You can define recursive functions, which call themselves within their own body.

groovy
def factorial(n) {
    if (n <= 1) {
        return 1
    } else {
        return n * factorial(n - 1)
    }
}

println factorial(5)  // Output 120