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.
// 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.
def a = 10 // Integer
def b = 10.5 // Floating-point number
def c = true // Boolean
def d = "Groovy" // StringLogical Operations
Groovy supports logical operators such as && (logical AND), || (logical OR), and ! (logical NOT).
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.
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.
// 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.
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.
def str = "Hello, Groovy!"
println str.substring(7) // Outputs Groovy!
println str.substring(0, 5) // Outputs HelloString Replacement
Use the replace method to substitute parts of a string.
def str = "Hello, Groovy!"
println str.replace("Groovy", "Java") // Outputs Hello, Java!String Splitting
The split method splits a string into an array.
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.
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.
def str = " Hello, Groovy! "
println str.trim() // Outputs Hello, Groovy!String Length
Access the length of a string using the length property.
def str = "Hello, Groovy!"
println str.length() // Outputs 14String Containment
Check whether a string contains a substring using the contains method.
def str = "Hello, Groovy!"
println str.contains("Groovy") // Outputs trueString Searching
Use the indexOf method to find the position of a substring within a string.
def str = "Hello, Groovy!"
println str.indexOf("Groovy") // Outputs 7String Comparison
Compare strings using operators like ==, !=, <, >, <=, and >=.
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 falseString Escaping
Escape special characters with \, such as \n for a newline.
def str = "Hello,\nGroovy!"
println str // Outputs Hello,
// Groovy!String Templates
Groovy allows embedding variables in strings using the ${} syntax.
def name = "Groovy"
def greeting = "Hello, ${name}!"
println greeting // Outputs Hello, Groovy!String Regular Expression Matching
Use the ==~ operator for regular expression matching.
def emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
def str = "google@163.com"
println str ==~ emailPattern // Outputs trueMultiline Strings
Define multiline strings using triple quotes """ or '''.
def multiLineStr = """
This is a multi-line
string in Groovy.
"""
println multiLineStrLists
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.
def list = [1, 2, 3, 'Groovy', true]Accessing List Elements
Access elements by index, starting from 0.
def list = [1, 2, 3, 'Groovy', true]
println list[3] // Outputs GroovyModifying List Elements
Update elements by their index.
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 <<.
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.
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.
def list = [1, 2, 3, 4, 5]
println list.size() // Outputs 5Iterating Over Lists
Use a for loop to iterate through list elements.
def list = [1, 2, 3, 4, 5]
for (item in list) {
println item
}Alternatively, use the each method.
def list = [1, 2, 3, 4, 5]
list.each { println it }List Transformations
collect: Apply a transformation to each element.
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.
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.
def list = [1, 2, 3, 4, 5]
println list.any { it % 2 == 0 } // Outputs trueevery: Verify all elements satisfy a condition.
def list = [1, 2, 3, 4, 5]
println list.every { it % 2 == 0 } // Outputs falseList Slicing
Extract a sublist using the subList method.
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.
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.
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.
def list = [1, 2, 3, 4, 5]
println list.contains(3) // Outputs true
println list.contains(6) // Outputs falseMerging Lists
Combine two lists using the plus method or the + operator.
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.
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 {}.
def map = [:]
map = ["name": "Groovy", "version": 2.5]Accessing Map Values
Access values by their keys.
def map = ["name": "Groovy", "version": 2.5]
println map["name"] // Outputs GroovyModifying Map Values
Update values by their keys.
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.
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.
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 2Iterating Over a Map
You can use the each method to iterate over key-value pairs in a map.
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.
def map = ["name": "Groovy", "version": 2.5]
println map.containsKey("name") // Output true
println map.containsValue(2.5) // Output trueClearing a Map
You can use the clear method to empty a map.
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.
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.
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.
def greet(name) {
return "Hello, ${name}!"
}Calling a Function
After defining a function, you can call it by specifying its name and arguments.
def result = greet("Groovy")
println result // Output Hello, Groovy!Functions with Default Parameters
You can provide default values for parameters when defining a function.
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.
def add(a, b) {
return a + b
}
println add(3, 5) // Output 8Anonymous Functions
You can define anonymous functions and assign them to variables or pass them as arguments.
def multiply = { a, b -> a * b }
println multiply(3, 5) // Output 15Functions with Variable Arguments
You can define functions that accept a variable number of arguments.
def sum(... numbers) {
def total = 0
for (number in numbers) {
total += number
}
return total
}
println sum(1, 2, 3, 4) // Output 10Functions with Closures
You can define functions that accept closures as arguments.
def operate(a, b, closure) {
return closure(a, b)
}
def add = { x, y -> x + y }
println operate(3, 5, add) // Output 8Functions Returning Multiple Values
You can define functions that return multiple values, which will be returned as a list.
def getCoordinates() {
return [10, 20]
}
def (x, y) = getCoordinates()
println "x: ${x}, y: ${y}" // Output x: 10, y: 20Recursive Functions
You can define recursive functions, which call themselves within their own body.
def factorial(n) {
if (n <= 1) {
return 1
} else {
return n * factorial(n - 1)
}
}
println factorial(5) // Output 120