Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

This section details the manipulations and operations on different data types in Groovy using methods of GDK and methods shared with JDK. 

On this page:

Table of Contents

Operations on Simple Data types

Strings

Some useful methods with examples are explained below. See here for all the methods applicable for a String and GString

Code Block
languagegroovy
linenumberstrue
def newString = "Hello Groovy in JMWE"

//startsWith
newString.startsWith("Hello") //returns true
newString.startsWith("Groovy") //returns false

//getAt()
newString.getAt(1) == "e"
newString[0] == "H"

//indexOf
newString.indexOf("in") == 13

//contains()
newString.contains("JMWE") //returns true

//Remove a part of the String
newString - "Hello " //returns "Groovy in JMWE"

//size()
newString.size() //returns 20

//Adding spaces to the String
"a".padLeft(3) //returns "   a"
"a".padRight(3) //retunrs "a   "
"a".center(3) //returns " a "
"a"*3 //returns "aaa"

//Strip extra lines
def multiline = """
String
containing 
multiple 
lines
"""

Numbers

As said earlier, numbers are objects and have methods. Some useful methods with examples are listed below. See here for all the methods applicable for a Number.

Code Block
languagegroovy
linenumberstrue
//Get the absolute value
(-1).abs() == 1

//Transform to integer
2.5.toInteger() == 2

//Enforced coercion
2.5 as Integer == 2

//Casting a number
(int) 2.5 == 2

//Rounding
2.5f.round() == 3
Math.PI.round(3) == 3.142

//String methods on numbers
"2.718".isNumber() //returns true

//Increment by one
2.next() ==  3

//times - Repeat certain number of times
def store = ""
10.times{
 store += "x"
}
store == "xxxxxxxxxx" //returns true

//upto - Walking upto a number
def store = ""
1.upto(5) { number ->
 store += number
}
store == "12345" 

//downto - Walking down to a number
def store = ""
2.downto(-2) { number -> 
 store += number + " "
}
store == "2 1 0 -1 -2 "

//step - Walking with step width 
def store = ""
0.step(0.5, 0.1 ){ number ->
 store += number + " "
} 
store == "0 0.1 0.2 0.3 0.4 "

Regular expressions

Some useful methods with examples are explained below. See here for all the methods applicable for regular expressions

Code Block
languagegroovy
linenumberstrue
//String.eachMatch method
def sentence = "Rain in spain stays mainly in plain"
def wordEnding = /w*ain/
def rhyme = /b$wordEndingb/
def found = ""
sentence.eachMatch(rhyme){ match ->
  found += match + " "
}

//Matcher.each method
found = ''
(sentence =~ rhyme).each { match ->
 found += match + ' '
}
found 

//String.replaceAll(regex){}
def replace = sentence.replaceAll(rhyme){ it-'ain'+'___' }
replace 

Booleans

Some useful methods with examples are explained below. See here for all the methods applicable for a Boolean.

Code Block
languagegroovy
linenumberstrue
//Logical conjuction of two boolean operators
"2.718".isNumber().and(2.718f.round() == 3)

//Coerce to a boolean value
(x=3).asBoolean()

Operations on Collections

Set

Some useful methods with examples are explained below. See here for all the methods applicable for a Set.

Code Block
languagegroovy
linenumberstrue
HashSet set = [1,2,3]

//Append a value at the end of the set
set.add(4) == [1,2,3,4]

//Get an element at a specified location
set.getAt(2)

//Contains an element
set.contains(4) == true

//Check whether the set is empty
set.isEmpty() == false

//Remove an element
set.minus(3)

//Add an element
set.plus(5)

//Size of the set
set.size() == 4

//Max and min in the set
set.max() == 4
set.min() == 1

//Find for the first element matching the condition
set.find{ it > 1 } //returns 2

//Find for all elements matching the condition
set.findAll{ it > 1 } //returns [2,3,4]

//Returns true if all elements match
set.every { it < 5 }

//Returns true if any element matches
set.any { it > 2 }

HashSet set1 = ["a", "b", "c", "d", "e"]
//Find index of 1st element matching criteria
set1.findIndexOf { it in ["c", "e", "g"] } //returns 2

//Sum of all the elements
set.sum() == 21
set1.sum() == "abcde"

//Join the elements
set.join('-') == "1-2-3"
HashSet set2 = [["a", "b"],["c", "d"]]
set2.sum() == ["a", "b", "c", "d"]

List

All the methods that apply to a Set are applicable to a List too. Some additional methods for List with examples are explained below. See here for all the methods applicable for a List.

Code Block
languagegroovy
linenumberstrue
def list = [1,2,3]

//Reverse a list
list.reverse() == [4, 3, 2, 1]

//Index returned
["a", "b", "c", "d", "c"].indexOf("c") == 2

//Get an element at a specified location
list.get(2)

Maps

Some useful methods with examples are explained below. See here for all the methods applicable for a Map.

Code Block
languagegroovy
linenumberstrue
def map = [name: "John", branch: "Electrical", id: 1234]

//Get the value of a key
map.get("name") == "John"
map["name"] == "John"
map.name == "John"

//Size of the map
map.size() == 3

//Escape key by adding paranthesis
def a = "John"
def ages = [(a):50]

ages.("John") //returns 50

//Clone a map
map2 = map.clone()

//Check the map contains a key
map.containsKey("id") == true

//Collection view of the values contained in the Map
map.values()

//Add elements
map.put("location", "Denmark")
map == [name: "John", branch: "Electrical", id: 1234, "location":"Denmark"]

def map3 = [1: "a", 2: "b", 3: "c"]
map.putAll(map3)
map == [name: "John", branch: "Electrical", id: 1234, "location":"Denmark", 1: "a", 2: "b", 3: "c"]

//Remove elements
map.clear() == null

//Obtain a Set of the keys in the Map
map.keySet()

def people = [
    1: [name:"Bob", age: 32, gender: "M"],
    2: [name:"Johnny", age: 36, gender: "M"],
    3: [name:"Claire", age: 21, gender: "F"],
    4: [name:"Amy", age: 54, gender:"F"]
]

//Find a specific element matching a condition
people.find { it.value.name == "Bob" } // returns a single entry

//Find all elements matching a condition
people.findAll { it.value.gender == "F" } //returns a Map matching the entries

//Collect specific values
def agesOfPeople = people.collect{
  it.value.age
}
agesOfPeople == [32, 36, 21, 54]

//Every - Returns true if all elements match the condition
people.every{ id, person ->
  person.age > 18
}

//Any - Returns true if any element matches the condition
people.any{ id, person ->
  person.age > 18
}

//Group a list into a map
list = ['a', 7, 'b', [2, 3]]
list.groupBy{
  it.class
}
//returns
[(String)   : ['a', 'b'],
 (Integer)  : [7],
 (ArrayList): [[2, 3]]
]

Ranges

Some useful methods with examples are explained below.

...

languagegroovy
linenumberstrue

...

Include Page
JMWE:Manipulating Data types
JMWE:Manipulating Data types