# Groovy Common Syntax

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

# Variable Declaration

In Groovy, variable declarations can use the def keyword or explicitly specify a type.

// Using def keyword
def name = "Groovy"

// Explicitly specifying 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
def c = true        // Boolean
def d = "Groovy"    // String

# Logical 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 concatenate strings using the + operator or through ${} syntax.

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

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

# String Substring

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

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

# String Replacement

You can use the replace method to replace content in a string.

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

# String Splitting

You can use the split method to split a string into an array.

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

# String Tokenization and Value Extraction

You can use the tokenize method to split a string into a list and access specific parts by index.

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

# String Trimming

You can use the trim method to remove whitespace characters from both ends of a string.

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

# String Length

You can use the length property to get the length of a string.

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

# String Contains

You can use the contains method to check if a string contains a substring.

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

You can use the indexOf method to find the position of a substring in a string.

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

# String Comparison

You can use operators like ==, !=, <, >, <=, >= to compare strings.

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

# String Escaping

You can use \ to escape special characters, such as \n for newline.

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

# String Templates

Groovy supports embedding variables in strings using ${} syntax.

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

# String Regular Expression Matching

You can 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  // Output true

# Multi-line Strings

You can define multi-line strings using triple quotes """ or '''.

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

# Lists

In Groovy, lists are a commonly used data structure that can contain elements of different types. Below are some common Groovy list operations.

# Defining Lists

You can define a list using square brackets [].

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

# Accessing List Elements

You can access elements in a list through indices, starting from 0.

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

# Modifying List Elements

You can modify elements in a list through indices.

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

# Adding Elements

You can use the add method or left shift operator << to add elements to a list.

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

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

# Removing Elements

You can use the remove method to remove elements from a list.

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

# List Length

You can use the size method to get the length of a list.

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

# Iterating Through Lists

You can use a for loop to iterate through elements in a list.

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

You can also use the each method to iterate through elements in a list.

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

# List Transformation

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

# List Filtering

find

Returns the first element that satisfies the condition.

def list = [1, 2, 3, 4, 5]
println list.find { it % 2 == 0 }  // Output 2

findAll

Returns a new list with all elements that satisfy the condition.

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

# List Matching

any

Checks if at least one element satisfies the condition

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

every

Checks if all elements satisfy the condition

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

# List Slicing

You can use the subList method to get part of a list.

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

# List Sorting

You can use the sort method to sort a list.

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

# List Reversal

You can use the reverse method to reverse a list.

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

# List Contains

You can use the contains method to check if a list contains an element.

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

# List Concatenation

You can use the plus method or + operator to concatenate two lists.

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

# Clearing Lists

You can use the clear method to clear a list.

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

# Maps

In Groovy, maps are a commonly used data structure for storing key-value pairs. Below are some common Groovy map operations.

# Defining Maps

You can define a map using square brackets [:] or curly braces {}.

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

# Accessing Map Elements

You can access values in a map through keys.

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

# Modifying Map Elements

You can modify values in a map through keys.

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

# Adding Elements

You can use the put method or direct assignment to add elements to a map.

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

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

# Removing Elements

You can use the remove method to remove elements from a map.

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.

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

# Iterating Through Maps

You can use the each method to iterate through 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 if 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 true

# Clearing Maps

You can use the clear method to clear 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 get all keys or values in 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 called methods and can be defined within classes or as part of scripts. Below are some common Groovy function definition and calling syntaxes.

# Defining Functions

You can use the def keyword to define a function.

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

# Calling Functions

After defining a function, you can call it using the function name and parameters.

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 parameters.

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 parameters.

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.

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 parameters.

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.

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 that call themselves within the function.

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

println factorial(5)  // Output 120