groovys documentation - read the docs · groovy 2.4 java 6 java 8 java 9 snapshot groovy-nio java 7...

29
groovys Documentation 1.0.0 zj 2016 01 14

Upload: others

Post on 11-Oct-2020

107 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation100

zj

2016 01 14

Contents

1 311 Groovy 312 Groovy 5

2 Indices and tables 25

i

ii

groovys Documentation 100

Contents

Contents 1

groovys Documentation 100

2 Contents

CHAPTER 1

11 Groovy

111

Groovy windows Mac OSX Linux Cygwin GVM Groovy Groovy

bull zipBinary Release | Source Release

bull JavaDoc and zipped online documentation

bull amp amp Distribution bundle

invokedynamic

Groovy (snapshot) CI Artifactoryrsquos OSS

Groovy 24 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8

Groovy CI Java Groovy 10000 Java Groovy

112 Maven Repository

Groovy maven repositories JCenter maven repository

3

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 2: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

Contents

1 311 Groovy 312 Groovy 5

2 Indices and tables 25

i

ii

groovys Documentation 100

Contents

Contents 1

groovys Documentation 100

2 Contents

CHAPTER 1

11 Groovy

111

Groovy windows Mac OSX Linux Cygwin GVM Groovy Groovy

bull zipBinary Release | Source Release

bull JavaDoc and zipped online documentation

bull amp amp Distribution bundle

invokedynamic

Groovy (snapshot) CI Artifactoryrsquos OSS

Groovy 24 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8

Groovy CI Java Groovy 10000 Java Groovy

112 Maven Repository

Groovy maven repositories JCenter maven repository

3

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 3: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

ii

groovys Documentation 100

Contents

Contents 1

groovys Documentation 100

2 Contents

CHAPTER 1

11 Groovy

111

Groovy windows Mac OSX Linux Cygwin GVM Groovy Groovy

bull zipBinary Release | Source Release

bull JavaDoc and zipped online documentation

bull amp amp Distribution bundle

invokedynamic

Groovy (snapshot) CI Artifactoryrsquos OSS

Groovy 24 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8

Groovy CI Java Groovy 10000 Java Groovy

112 Maven Repository

Groovy maven repositories JCenter maven repository

3

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 4: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

Contents

Contents 1

groovys Documentation 100

2 Contents

CHAPTER 1

11 Groovy

111

Groovy windows Mac OSX Linux Cygwin GVM Groovy Groovy

bull zipBinary Release | Source Release

bull JavaDoc and zipped online documentation

bull amp amp Distribution bundle

invokedynamic

Groovy (snapshot) CI Artifactoryrsquos OSS

Groovy 24 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8

Groovy CI Java Groovy 10000 Java Groovy

112 Maven Repository

Groovy maven repositories JCenter maven repository

3

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 5: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

2 Contents

CHAPTER 1

11 Groovy

111

Groovy windows Mac OSX Linux Cygwin GVM Groovy Groovy

bull zipBinary Release | Source Release

bull JavaDoc and zipped online documentation

bull amp amp Distribution bundle

invokedynamic

Groovy (snapshot) CI Artifactoryrsquos OSS

Groovy 24 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8

Groovy CI Java Groovy 10000 Java Groovy

112 Maven Repository

Groovy maven repositories JCenter maven repository

3

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 6: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

CHAPTER 1

11 Groovy

111

Groovy windows Mac OSX Linux Cygwin GVM Groovy Groovy

bull zipBinary Release | Source Release

bull JavaDoc and zipped online documentation

bull amp amp Distribution bundle

invokedynamic

Groovy (snapshot) CI Artifactoryrsquos OSS

Groovy 24 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8

Groovy CI Java Groovy 10000 Java Groovy

112 Maven Repository

Groovy maven repositories JCenter maven repository

3

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 7: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

Gradle Maven Explanationorgcodehausgroovygroovy245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovyltartifactIdgtltversiongt245ltversiongt

Just the core of groovy without themodules (see below)

orgcodehausgroovygroovy- $mod-ule245lsquo

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-$moduleltartifactIdgt ltver-siongt245ltversiongt

Example ltartifactIdgtgroovy-sqlltartifactIdgt

orgcodehausgroovygroovy-all245

ltgroupIdgtorgcodehausgroovyltgroupIdgtltartifactIdgtgroovy-allltartifactIdgtltversiongt245ltversiongt

InvokeDynamic jars Gradle indy Maven ltclassifiergtindyltclassifiergt

113 GVM (the Groovy enVironment Manager)

GVM (Mac OSX Linux Cygwin Solaris or FreeBSD) Bash Groovy

terminal

$ curl -s getgvmtoolnet | bash

terminal

$ source $HOMEgvmbingvm-initsh

Groovy

$ gvm install groovy

$ groovy -version

114 Groovy

Mac OS X

MacOS MacPorts

sudo port install groovy

MacOS Homebrew

brew install groovy

Windows

Windows NSIS Windows installer

4 Chapter 1

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 8: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

Other Distributions

You may download other distributions of Groovy from this site

Source Code

GitHub

115 IDE plugin

IDE IDE

116

Groovy

bull

bull GROOVY_HOME

bull GROOVY_HOMEbin PATH

bull JAVA_HOME JDK OS X LibraryJavaHome unix

usrjava Ant Maven

Groovy

groovysh

Groovy shell Groovy Swing interactive console

groovyConsole

Groovy script

groovy SomeScript

12 Groovy

121 Working with IO

Groovy IO JAVA Groovy Groovy reader

bull the javaioFile class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioFilehtml

bull the javaioInputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioInputStreamhtml

bull the javaioOutputStream class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioOutputStreamhtml

bull the javaioReader class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioReaderhtml

bull the javaioWriter class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaioWriterhtml

bull the javaniofilePath class httpdocsgroovy-langorglatesthtmlgroovy-jdkjavaniofilePathhtml

12 Groovy 5

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 9: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

GDK API

new File(baseDir haikutxt)eachLine line -gtprintln line

eachLine Groovy File

new File(baseDir haikutxt)eachLine line nb -gtprintln Line $nb $line

eachLine Groovy IO

Reader Groovy reader

def count = 0 MAXSIZE = 3new File(baseDirhaikutxt)withReader reader -gt

while (readerreadLine()) if (++count gt MAXSIZE)

throw new RuntimeException(Haiku should only have 3 verses)

list

def list = new File(baseDir haikutxt)collect it

as

def array = new File(baseDir haikutxt) as String[]

byte[]

Groovy

byte[] contents = filebytes

IO Groovy

InputStream

def is = new File(baseDirhaikutxt)newInputStream() do something isclose()

inputstream Groovy withInputStream

new File(baseDirhaikutxt)withInputStream stream -gt do something

Writer

6 Chapter 1

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 10: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

new File(baseDirhaikutxt)withWriter(utf-8) writer -gtwriterwriteLine Into the ancient pondwriterwriteLine A frog jumpswriterwriteLine Waterrsquos sound

ltlt

new File(baseDirhaikutxt) ltlt Into the ancient pondA frog jumpsWaterrsquos sound

Writer

filebytes = [662211]

def os = new File(baseDirdatabin)newOutputStream() do something osclose()

withOutputStream

new File(baseDirdatabin)withOutputStream stream -gt do something

Groovy

direachFile file -gt lt1gtprintln filename

direachFileMatch(~txt) file -gt lt2gt

println filename

lt1gt

lt2gt

eachFileRecurse

direachFileRecurse file -gt lt1gtprintln filename

direachFileRecurse(FileTypeFILES) file -gt lt2gtprintln filename

lt1gt

lt2gt

traverse

dirtraverse file -gtif (filedirectory ampamp filename==bin)

FileVisitResultTERMINATE lt1gt

12 Groovy 7

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 11: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

else println filenameFileVisitResultCONTINUE lt2gt

lt1gt bin

lt2gt

Data amp objects

JAVA javaioDataOutputStream amp javaioDataInputStream Groovy

boolean b = trueString message = Hello from Groovy Serialize data into a filefilewithDataOutputStream out -gt

outwriteBoolean(b)outwriteUTF(message)

Then read it backfilewithDataInputStream input -gt

assert inputreadBoolean() == bassert inputreadUTF() == message

Serializable

Person p = new Person(nameBob age76) Serialize data into a filefilewithObjectOutputStream out -gt

outwriteObject(p) Then read it backfilewithObjectInputStream input -gt

def p2 = inputreadObject()assert p2name == pnameassert p2age == page

Groovy reader Groovy exxcute()

def process = ls -lexecute() lt1gtprintln Found text $processtext lt2gt

lt1gt ls

lt2gt

execute() javalangProcess inouterr streams

8 Chapter 1

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 12: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

def process = ls -lexecute() lt1gtprocessineachLine line -gt lt2gt

println line lt3gt

lt1gt

lt2gt

lt3gt

out

shell windows

def process = direxecute()println $processtext

IOException Cannot run program ldquodirrdquo CreateProcess error=2 The system cannot find the file specified dir Cre-ateProcess error=2

dir cmdexe

def process = cmd c direxecute()println $processtext

javalangProcess javadoc

Because some native platforms only provide limited buffer size for standard input and output streams failure topromptly write the input stream or read the output stream of the subprocess may cause the subprocess to block andeven deadlock

Groovy

def p = rm -f footmpexecute([] tmpDir)pconsumeProcessOutput()pwaitFor()

consumeProcessOutput StringBuffer InputStream OutputStream GDK API forjavalangProcess

pipeTo

Pipes in action

proc1 = lsexecute()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc1 | proc2 | proc3 | proc4proc4waitFor()if (proc4exitValue())

println proc4errtext else

println proc4text

12 Groovy 9

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 13: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

Consuming errors

def sout = new StringBuilder()def serr = new StringBuilder()proc2 = tr -d oexecute()proc3 = tr -d eexecute()proc4 = tr -d iexecute()proc4consumeProcessOutput(sout serr)proc2 | proc3 | proc4[proc2 proc3]each itconsumeProcessErrorStream(serr) proc2withWriter writer -gt

writer ltlt testfilegroovyproc4waitForOrKill(1000)println Standard output $soutprintln Standard error $serr

122 Working with collections

Groovy lists maps ranges Java Groovy

Lists

lists []

def list = [5 6 7 8]assert listget(2) == 7assert list[2] == 7assert list instanceof javautilList

def emptyList = []assert emptyListsize() == 0emptyListadd(5)assert emptyListsize() == 1

list javautilList lists lists

def list1 = [a b c]construct a new list seeded with the same items as in list1def list2 = new ArrayListltStringgt(list1)

assert list2 == list1 == checks that each corresponding element is the same

clone() can also be calleddef list3 = list1clone()assert list3 == list1

list

def list = [5 6 7 8]assert listsize() == 4assert listgetClass() == ArrayList the specific kind of list being used

assert list[2] == 7 indexing starts at 0assert listgetAt(2) == 7 equivalent method to subscript operator []assert listget(2) == 7 alternative method

10 Chapter 1

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 14: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

list[2] = 9assert list == [5 6 9 8] trailing comma OK

listputAt(2 10) equivalent method to [] when value being changedassert list == [5 6 10 8]assert listset(2 11) == 10 alternative method that returns old valueassert list == [5 6 11 8]

assert [a 1 a a 25 25f 25d hello 7g null 9 as byte]objects can be of different types duplicates allowed

assert [1 2 3 4 5][-1] == 5 use negative indices to count from the endassert [1 2 3 4 5][-2] == 4assert [1 2 3 4 5]getAt(-2) == 4 getAt() available with negative indextry

[1 2 3 4 5]get(-2) but negative index not allowed with get()assert false

catch (e) assert e instanceof ArrayIndexOutOfBoundsException

assert [] an empty list evaluates as false

all other lists irrespective of contents evaluate as trueassert [1] ampamp [a] ampamp [0] ampamp [00] ampamp [false] ampamp [null]

each eachWithIndex code-block groovy

[1 2 3]each println ldquoItem $itrdquo it is an implicit parameter corresponding to the current element

[rsquoarsquo lsquobrsquo lsquocrsquo]eachWithIndex it i -gt it is the current element while i is the index

println ldquo$i $itrdquo

mapping Groovy collect

assert [1 2 3]collect it 2 == [2 4 6]

shortcut syntax instead of collectassert [1 2 3]multiply(2) == [1 2 3]collect itmultiply(2)

def list = [0] it is possible to give `collect` the list which collects the elementsassert [1 2 3]collect(list) it 2 == [0 2 4 6]assert list == [0 2 4 6]

Groovy

12 Groovy 11

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 15: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

assert [1 2 3]find it gt 1 == 2 find 1st element matching criteriaassert [1 2 3]findAll it gt 1 == [2 3] find all elements matching critieriaassert [a b c d e]findIndexOf find index of 1st element matching criteria

it in [c e g] == 2

assert [a b c d c]indexOf(c) == 2 index returnedassert [a b c d c]indexOf(z) == -1 index -1 means value not in listassert [a b c d c]lastIndexOf(c) == 4

assert [1 2 3]every it lt 5 returns true if all elements match the predicateassert [1 2 3]every it lt 3 assert [1 2 3]any it gt 2 returns true if any element matches the predicateassert [1 2 3]any it gt 3

assert [1 2 3 4 5 6]sum() == 21 sum anything with a plus() methodassert [a b c d e]sum

it == a 1 it == b 2 it == c 3 it == d 4 it == e 5 0 custom value to use in sum

== 15assert [a b c d e]sum ((char) it) - ((char) a) == 10assert [a b c d e]sum() == abcdeassert [[a b] [c d]]sum() == [a b c d]

an initial value can be providedassert []sum(1000) == 1000assert [1 2 3]sum(1000) == 1006

assert [1 2 3]join(-) == 1-2-3 String joiningassert [1 2 3]inject(counting )

str item -gt str + item reduce operation == counting 123assert [1 2 3]inject(0) count item -gt

count + item == 6

Groovy

def list = [9 4 2 10 5]assert listmax() == 10assert listmin() == 2

we can also compare single characters as anything comparableassert [x y a z]min() == a

we can use a closure to specify the sorting behaviourdef list2 = [abc z xyzuvw Hello 321]assert list2max itsize() == xyzuvwassert list2min itsize() == z

Comparator

Comparator mc = a b -gt a == b 0 (a lt b -1 1)

def list = [7 4 9 -6 -1 11 2 3 -9 5 -13]assert listmax(mc) == 11assert listmin(mc) == -13

Comparator mc2 = a b -gt a == b 0 (Mathabs(a) lt Mathabs(b)) -1 1

12 Chapter 1

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 16: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

assert listmax(mc2) == -13assert listmin(mc2) == -1

assert listmax a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -13assert listmin a b -gt aequals(b) 0 Mathabs(a) lt Mathabs(b) -1 1 == -1

[] ltlt

def list = []assert listempty

list ltlt 5assert listsize() == 1

list ltlt 7 ltlt i ltlt 11assert list == [5 7 i 11]

list ltlt [m o]assert list == [5 7 i 11 [m o]]

first item in chain of ltlt is target listassert ([1 2] ltlt 3 ltlt [4 5] ltlt 6) == [1 2 3 [4 5] 6]

using leftShift is equivalent to using ltltassert ([1 2 3] ltlt 4) == ([1 2 3]leftShift(4))

assert [1 2] + 3 + [4 5] + 6 == [1 2 3 4 5 6] equivalent to calling the `plus` methodassert [1 2]plus(3)plus([4 5])plus(6) == [1 2 3 4 5 6]

def a = [1 2 3]a += 4 creates a new list and assigns it to `a`a += [5 6]assert a == [1 2 3 4 5 6]

assert [1 [222 333] 456] == [1 222 333 456]assert [[1 2 3]] == [1 2 3]assert [1 [2 3 [4 5] 6] 7 [8 9]]flatten() == [1 2 3 4 5 6 7 8 9]

def list = [1 2]listadd(3)listaddAll([5 4])assert list == [1 2 3 5 4]

list = [1 2]listadd(1 3) add 3 just before index 1assert list == [1 3 2]

listaddAll(2 [5 4]) add [54] just before index 2assert list == [1 3 5 4 2]

list = [a b z e u v g]

12 Groovy 13

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 17: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

list[8] = x the [] operator is growing the list as needed nulls inserted if requiredassert list == [a b z e u v g null x]

ltlt + list

Groovy

assert [abcbb] - c == [abbb]assert [abcbb] - b == [ac]assert [abcbb] - [bc] == [a]

def list = [1234321]list -= 3 creates a new list by removing `3` from the original oneassert list == [12421]assert ( list -= [24] ) == [11]

def list = [123456221]assert listremove(2) == 3 remove the third element and return itassert list == [12456221]

remove

def list= [abcbb]assert listremove(c) remove c and return true because element removedassert listremove(b) remove first b and return true because element removed

assert listremove(z) return false because no elements removedassert list == [abb]

clear

def list= [a2c4]listclear()assert list == []

Set operations

Groovy

assert a in [abc] returns true if an element belongs to the listassert [abc]contains(a) equivalent to the `contains` method in Javaassert [134]containsAll([14]) `containsAll` will check that all elements are found

assert [12333345]count(3) == 4 count the number of elements which have some valueassert [12333345]count

it2==0 count the number of elements which match the predicate == 2

assert [124681012]intersect([136912]) == [1612]

assert [123]disjoint( [469] ) assert [123]disjoint( [246] )

14 Chapter 1

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 18: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

Groovy

assert [6 3 9 2 7 1 5]sort() == [1 2 3 5 6 7 9]

def list = [abc z xyzuvw Hello 321]assert listsort

itsize() == [z abc 321 Hello xyzuvw]

def list2 = [7 4 -6 -1 11 2 3 -9 5 -13]assert list2sort a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1 ==

[-1 2 3 4 5 -6 7 -9 11 -13]

Comparator mc = a b -gt a == b 0 Mathabs(a) lt Mathabs(b) -1 1

JDK 8+ only list2sort(mc) assert list2 == [-1 2 3 4 5 -6 7 -9 11 -13]

def list3 = [6 -3 9 2 -7 1 5]

Collectionssort(list3)assert list3 == [-7 -3 1 2 5 6 9]

Collectionssort(list3 mc)assert list3 == [1 2 -3 5 6 -7 9]

Groovy

assert [1 2 3] 3 == [1 2 3 1 2 3 1 2 3]assert [1 2 3]multiply(2) == [1 2 3 1 2 3]assert CollectionsnCopies(3 b) == [b b b]

nCopies from the JDK has different semantics than multiply for listsassert CollectionsnCopies(2 [1 2]) == [[1 2] [1 2]] not [1212]

123 Maps

Map literals

Groovy [] map

def map = [name Gromit likes cheese id 1234]assert mapget(name) == Gromitassert mapget(id) == 1234assert map[name] == Gromitassert map[id] == 1234assert map instanceof javautilMap

def emptyMap = []assert emptyMapsize() == 0

12 Groovy 15

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 19: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

emptyMapput(foo 5)assert emptyMapsize() == 1assert emptyMapget(foo) == 5

Map key String [a1] [rsquoarsquo1] Map keys are strings by default [a1] is equivalent to [rsquoarsquo1] a a map key

def a = Bobdef ages = [a 43]assert ages[Bob] == null `Bob` is not foundassert ages[a] == 43 because `a` is a literal

ages = [(a) 43] now we escape `a` by using parenthesisassert ages[Bob] == 43 and the value is found

Map clone

def map = [simple 123complex [a 1 b 2]

]def map2 = mapclone()assert map2get(simple) == mapget(simple)assert map2get(complex) == mapget(complex)map2get(complex)put(c 3)assert mapget(complex)get(c) == 3

map

Map property notation

Maps beans key map

def map = [name Gromit likes cheese id 1234]assert mapname == Gromit can be used instead of mapget(Gromit)assert mapid == 1234

def emptyMap = []assert emptyMapsize() == 0emptyMapfoo = 5assert emptyMapsize() == 1assert emptyMapfoo == 5

mapfoo map key foo fooclass null map class key key class getClass()

def map = [name Gromit likes cheese id 1234]assert mapclass == nullassert mapget(class) == nullassert mapgetClass() == LinkedHashMap this is probably what you want

map = [1 a(true) p(false) q(null) xnull z]

assert mapcontainsKey(1) 1 is not an identifier so used as isassert maptrue == nullassert mapfalse == nullassert mapget(true) == p

16 Chapter 1

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 20: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

assert mapget(false) == qassert mapnull == zassert mapget(null) == x

maps

Groovy each eachWithIndex map map

def map = [Bob 42Alice 54Max 33

]

`entry` is a map entrymapeach entry -gt

println Name $entrykey Age $entryvalue

`entry` is a map entry `i` the index in the mapmapeachWithIndex entry i -gt

println $i - Name $entrykey Age $entryvalue

Alternatively you can use key and value directlymapeach key value -gt

println Name $key Age $value

Key value and i as the index in the mapmapeachWithIndex key value i -gt

println $i - Name $key Age $value

Map

map put putAll

def defaults = [1 a 2 b 3 c 4 d]def overrides = [2 z 5 x 13 x]

def result = new LinkedHashMap(defaults)resultput(15 t)result[17] = uresultputAll(overrides)assert result == [1 a 2 z 3 c 4 d 5 x 13 x 15 t 17 u]

clear map

def m = [1a 2b]assert mget(1) == amclear()assert m == []

Maps object equals hashcode hash code key GString map key GString hash code String hash code

12 Groovy 17

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 21: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

def key = some keydef map = []def gstringKey = $keytoUpperCase()mapput(gstringKeyvalue)assert mapget(SOME KEY) == null

def map = [1a 2b 3c]

def entries = mapentrySet()entrieseach entry -gt

assert entrykey in [123]assert entryvalue in [abc]

def keys = mapkeySet()assert keys == [123] as Set

Mutating values returned by the view (be it a map entry a key or a value) is highly discouraged because success ofthe operation directly depends on the type of the map being manipulated In particular Groovy relies on collectionsfrom the JDK that in general make no guarantee that a collection can safely be manipulated through keySet entrySetor values

Groovy httpwwwgroovy-langorggroovy-dev-kithtmlList-Filtering[list] The Groovy development kit containsfiltering searching and collecting methods similar to those found for lists

def people = [1 [nameBob age 32 gender M]2 [nameJohnny age 36 gender M]3 [nameClaire age 21 gender F]4 [nameAmy age 54 genderF]

]

def bob = peoplefind itvaluename == Bob find a single entrydef females = peoplefindAll itvaluegender == F

both return entries but you can use collect to retrieve the ages for exampledef ageOfBob = bobvalueagedef agesOfFemales = femalescollect

itvalueage

assert ageOfBob == 32assert agesOfFemales == [2154]

but you could also use a keypair value as the parameters of the closuresdef agesOfMales = peoplefindAll id person -gt

persongender == Mcollect id person -gt

personageassert agesOfMales == [32 36]

`every` returns true if all entries match the predicateassert peopleevery id person -gt

personage gt 18

`any` returns true if any entry matches the predicate

18 Chapter 1

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 22: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

assert peopleany id person -gtpersonage == 54

assert [a 7 b [2 3]]groupBy itclass

== [(String) [a b](Integer) [7](ArrayList) [[2 3]]

]

assert [[name Clark city London] [name Sharma city London][name Maradona city LA] [name Zhang city HK][name Ali city HK] [name Liu city HK]

]groupBy itcity == [London [[name Clark city London]

[name Sharma city London]]LA [[name Maradona city LA]]HK [[name Zhang city HK]

[name Ali city HK][name Liu city HK]]

]

Ranges

Ranges Ranges List Range javautilList Ranges Ranges lt

an inclusive rangedef range = 58assert rangesize() == 4assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

lets use a half-open rangerange = 5lt8assert rangesize() == 3assert rangeget(2) == 7assert range[2] == 7assert range instanceof javautilListassert rangecontains(5)assert rangecontains(8)

get the end points of the range without using indexesrange = 110assert rangefrom == 1assert rangeto == 10

int ranges java

Ranges javalangComparable java next() previous() String

an inclusive rangedef range = ad

12 Groovy 19

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 23: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

assert rangesize() == 4assert rangeget(2) == cassert range[2] == cassert range instanceof javautilListassert rangecontains(a)assert rangecontains(d)assert rangecontains(e)

for

for (i in 110) println Hello $i

Groovy each

(110)each i -gtprintln Hello $i

Ranges switch

switch (years) case 110 interestRate = 0076 breakcase 1125 interestRate = 0052 breakdefault interestRate = 0037

lists maps Groovy

def listOfMaps = [[a 11 b 12] [a 21 b 22]]assert listOfMapsa == [11 21] GPath notationassert listOfMapsa == [11 21] spread dot notation

listOfMaps = [[a 11 b 12] [a 21 b 22] null]assert listOfMapsa == [11 21 null] caters for null valuesassert listOfMapsa == listOfMapscollect ita equivalent notation But this will only collect non-null valuesassert listOfMapsa == [1121]

Spread operator putAll

assert [ z 900

[a 100 b 200] a 300] == [a 300 b 200 z 900]spread map notation in map definitionassert [ [3 3 [5 5]] 7 7] == [3 3 5 5 7 7]

def f = [1 u 2 v 3 w] assert [ f() 10 zz] == [1 u 10 zz 2 v 3 w]spread map notation in function argumentsf = map -gt mapc assert f( [a 10 b 20 c 30] e 50) == 30

f = m i j k -gt [m i j k] using spread map notation with mixed unnamed and named argumentsassert f(e 100 [4 5] [a 10 b 20 c 30] 6) ==

[[e 100 b 20 c 30 a 10] 4 5 6]

20 Chapter 1

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 24: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

assert [1 3 5] == [a few words]size()

class Person String nameint age

def persons = [new Person(nameHugo age17) new Person(nameSandraage19)]assert [17 19] == personsage

listsmapsarrays

def text = nice cheese gromitdef x = text[2]

assert x == cassert xclass == String

def sub = text[510]assert sub == cheese

def list = [10 11 12 13]def answer = list[23]assert answer == [1213]

ranges

list = 100200sub = list[1 3 2025 33]assert sub == [101 103 120 121 122 123 124 125 133]

list = [axxd]list[12] = [bc]assert list == [abcd]

List array String

text = nice cheese gromitx = text[-1]assert x ==

def name = text[-7-2]assert name == gromit

text = nice cheese gromitname = text[31]assert name == eci

lists maps ranges Groovy

Groovy API

bull methods added to Iterable can be found here

12 Groovy 21

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 25: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

bull methods added to Iterator can be found here

bull methods added to Collection can be found here

bull methods added to List can be found here

bull methods added to Map can be found here

124 Handy utilities ()

ConfigSlurper

ConfigSlurper Groovy script Java properties ConfigSlurper

def config = new ConfigSlurper()parse(appdate = new Date() lt1gtappage = 42app lt2gt

name = Test$42

)

assert configappdate instanceof Dateassert configappage == 42assert configappname == Test42

lt1gt

lt2gt

parse groovyutilConfigObject ConfigObject javautilMap ConfigObject null

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42appname = Test$42

)

assert configtest = null lt1gt

lt1gt configtest ConfigObject

def config = new ConfigSlurper()parse(apppersonage = 42

)

assert configapppersonage == 42

ConfigSlurper environments ConfigSlurper(String)

def config = new ConfigSlurper(development)parse(environments

development appport = 8080

test appport = 8082

22 Chapter 1

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 26: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

production appport = 80

)

assert configappport == 8080

ConfigSlurper environments environments registerConditionalBlock environments

def slurper = new ConfigSlurper()slurperregisterConditionalBlock(myProject developers) lt1gt

def config = slurperparse(sendMail = true

myProject developers

sendMail = false

)

assert configsendMail

lt1gt ConfigSlurper

Java toProperties ConfigObject javautilProperties properties Properties

def config = new ConfigSlurper()parse(appdate = new Date()appage = 42app

name = Test$42

)

def properties = configtoProperties()

assert propertiesappdate instanceof Stringassert propertiesappage == 42assert propertiesappname == Test42

Expando

Expando

def expando = new Expando()expandoname = John

assert expandoname == John

def expando = new Expando()expandotoString = -gt John expandosay = String s -gt John says $s

assert expando as String == Johnassert expandosay(Hi) == John says Hi

12 Groovy 23

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 27: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

groovys Documentation 100

list map and set

Groovy lists map sets javabeansPropertyChangeEvent

PropertyChangeEvent ObservableListElementAddedEvent

def event lt1gtdef listener =

if (it instanceof ObservableListElementEvent) lt2gtevent = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableList lt3gtobservableaddPropertyChangeListener(listener) lt4gt

observableadd 42 lt5gt

assert event instanceof ObservableListElementAddedEvent

def elementAddedEvent = event as ObservableListElementAddedEventassert elementAddedEventchangeType == ObservableListChangeTypeADDEDassert elementAddedEventindex == 3assert elementAddedEventoldValue == nullassert elementAddedEventnewValue == 42

lt1gt PropertyChangeEventListener

lt2gt ObservableListElementEvent

lt3gt

lt4gt

lt5gt

ObservableListElementAddedEvent PropertyChangeEvent clear()ObservableListElementClearedEvent

def eventdef listener =

if (it instanceof ObservableListElementEvent) event = it

as PropertyChangeListener

def observable = [1 2 3] as ObservableListobservableaddPropertyChangeListener(listener)

observableclear()

assert event instanceof ObservableListElementClearedEvent

def elementClearedEvent = event as ObservableListElementClearedEventassert elementClearedEventvalues == [1 2 3]assert observablesize() == 0

ObservableMap and ObservableSet ObservableList

24 Chapter 1

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables
Page 28: groovys Documentation - Read the Docs · Groovy 2.4 Java 6 Java 8 Java 9 snapshot groovy-nio Java 7 invokeDynamic Java 7+ Java 8 Groovy CI Java Groovy 10000 Java Groovy 1.1.2Maven

CHAPTER 2

Indices and tables

bull genindex

bull modindex

bull search

25

  • Groovy
  • Groovy
    • Indices and tables