SlideShare ist ein Scribd-Unternehmen logo
1 von 31
Groovy
Agenda
1. Installation
2. Difference with JAVA
3. Groovy Development Kit
4. Syntax
5. Operators
6. Groovy Truth
7. Program Structure (later)
8. Closures
Installation
Differences with JAVA
● Default Imports
● Multi-Methods
● Array Initializers
● GStrings and String and Character Literals
● Primitives and Wrappers
● Behavior of ==
● Extra Keywords
Default Imports
Multi-Methods/Runtime-Dispatch
In Groovy
int method(String arg) {
return 1;
}
int method(Object arg) {
return 2;
}
Object o = "Object";
int result = method(o);
assert 1==result
In Java
int method(String arg) {
return 1;
}
int method(Object arg) {
return 2;
}
Object o = "Object";
int result = method(o);
assertEquals(2,result)
Array Initializers
GStringsand String and Character Literals
Singly quoted literals in Groovy are used for Strings, and double quoted result in
String as well as GString.
● assert 'c'.getClass()==String
● assert "c".getClass()==String
● assert "c${1}".getClass() in GString
When calling methods with argument of type char we need to either cast explicitly
or make sure the value has been cast in advance.
Groovy Casting can be done by two ways:-
● assert ((char) "c").class==Character
● assert ("c" as char).class==Character
For multi char String:-
● assert ((char) 'cx') == 'c' // GroovyCast Exception
● assert ('cx' as char) == 'c'
● assert 'cx'.asType(char) == 'c'
Primitive and Wrappers
Groovy autowraps references to primitives.
Behaviour of ==
In java == means equality of primitive types or identity for objects.
In groovy == translates to a.compareTo(b)==0, if they are comparable and
a.equals(b) otherwise.
To check Identity we had a.is(b)
● Comments
○ Single Line Comments
○ Multi-line Comments
○ GroovyDoc Comments
● Keywords
○ as
○ def
○ in
○ trait
● Identifier
○ All keywords are also valid identifiers when following a dot. (foo.as)
○ Quoted Identifiers
Quoted Identifier
String
1. Single quoted
2. Double quoted
3. Triple Single quoted
4. Triple Double Quoted
Operators
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Conditional Operators
5. Object Operators
Elvis Operator(?:)
Safe Navigation Operator(?.)
Method Pointer Operator (.&)
Spread Operator (*.)
Range Operator (..)
Spaceship Operator (<==>) delegates to compareTo
MemberShip Operator (in)
User Field Access Operator (.@)
http://www.groovy-lang.org/operators.html#_other_operators
Groovy Collections
Data structure that helps in dealing with a number of objects.
A wide variety of methods available for easy manipulation.
List
A list cares about the index
Elements are assigned indices on the basis of how they are added
Has methods related to the index
Index starts from 0
Creating list
//create empty list with each element of type 'def'
List list = [ ]
//create empty list with elements of type 'type'
List<type> list = [ ]
List<type> list = new ArrayList()
Adding an element
list.add(“element1”)
list << “element1”
list += “element1”
list.push(element)
List firstList = [1,2,3,4,5]
List secondList = [“element2”]
List thirdList = firstList + secondList
println thirdList // [1,2,3,4,5,”element2”]
fourthlist = thirdlist - firstlist
println fourthlist // [“element2”]
Fetching elements:
list[i] – Get ith element in list starting from 0
list.get(0) – Get first element in list
list.getAt(0) – Get first element in list
list.first() - Get first element of list
list.head() - Get the head of list
list.last() - Get last element of list
list.tail() - Get all elements except first
list.getAt(1..10) – Get elements from index 1 to 10
(includes index 10)
list.subList(1, 10) - Get elements at index 1 to 10 (index
10 excluded)
Removing duplicates from a List :
list.unique() // Alters original list
list as Set
Deleting an element from a List :
(All of them alter original list)
list.remove(idx)
list.pop()
list.removeAll(collection)
Convert String into List:
“Hi” as List / “Hi”.toList()
string.tokenize('_') : Splits the string into a list with argument used as delimiter.
string.split('_') : Same as tokenize but can also accept regular expressions as
delimiters
Convert List into String:
list.join(',')
Operations on each element of list:
println list*.name // Use of spread operator
list.collect { it.multiply(2) } // what if 'it' refers to string?
list.find { it.name==”abc” } // returns one object
list.findAll { it.name==”abc” } // returns list
list.each { println it.name }
list.eachWithIndex{p, index ->
println index +”. “ + p.name
}
list.reverseEach { println it.name }
List Methods
size() - Get size of list
reverse() - reverses the order of list elements
contains(value) – Find if list contains specified value
sum(closure) - Sum all the elements of the list
min(closure) – Get min value of list
max(closure) – Get max value of list
flatten() - Make nested lists into a simple list
sort(closure) - Sort the list in ascending order
.list1.intersect(list2) : returns a list that contains elements that exist in both the
lists.
.list1.disjoint(list2) : Returns true/false indicating whether lists are disjoint
or not.
.every{condition} : checks whether every element of the list satisfy the
condition.
.any{condition} : checks whether any of the element of the satisfy the
condition.
Set
A Set cares about uniqueness - it doesn't allow duplicates
It can be considered as a list with restrictions, and is often constructed from a
list.
Set set = [1,3,3,4] as Set
([1,3,4])
No Ordering; element positions do not matter
Most methods available to lists, besides those that don't make sense for
unordered items, are available to sets.
Like - getAt, putAt, reverse
Ranges
Ranges allow you to create a list of sequential values.
These can be used as Lists since Range extends java.util.List.
Generally used for looping, switch, lists etc
Ranges defined with the “..” notation are inclusive (that is the list contains the
from and to value).
Ranges defined with the “..<” notation are exclusive, they include the first value but
not the last value.
Range range = 1..10
range = -10..<10
range = '#'..'~'
Methods
range.from – Get the lower limit of range
range.to – Get upper limit of range
range.contains(value) – Does range contain value?
1. Groovy Truth (later)
2. Program Structure (later)
3. Closures(later)

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (19)

Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...Below is a given ArrayList class and Main class  Your Dreams Our Mission/tuto...
Below is a given ArrayList class and Main class Your Dreams Our Mission/tuto...
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
List in Python
List in PythonList in Python
List in Python
 
Data type list_methods_in_python
Data type list_methods_in_pythonData type list_methods_in_python
Data type list_methods_in_python
 
C# Filtering in generic collections
C# Filtering in generic collectionsC# Filtering in generic collections
C# Filtering in generic collections
 
Python list
Python listPython list
Python list
 
Unit 4 python -list methods
Unit 4   python -list methodsUnit 4   python -list methods
Unit 4 python -list methods
 
Chapter 15 Lists
Chapter 15 ListsChapter 15 Lists
Chapter 15 Lists
 
Exp 6.2 d-422 (1)
Exp 6.2  d-422 (1)Exp 6.2  d-422 (1)
Exp 6.2 d-422 (1)
 
List,tuple,dictionary
List,tuple,dictionaryList,tuple,dictionary
List,tuple,dictionary
 
F sharp lists & dictionary
F sharp   lists &  dictionaryF sharp   lists &  dictionary
F sharp lists & dictionary
 
LIST IN PYTHON
LIST IN PYTHONLIST IN PYTHON
LIST IN PYTHON
 
Billing Software By Harsh Mathur.
Billing Software By Harsh Mathur.Billing Software By Harsh Mathur.
Billing Software By Harsh Mathur.
 
Python List Comprehensions
Python List ComprehensionsPython List Comprehensions
Python List Comprehensions
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 

Ähnlich wie Groovy

2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
arshin9
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdf
mayorothenguyenhob69
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
Out Cast
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
timourian
 
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdfLab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
QalandarBux2
 

Ähnlich wie Groovy (20)

Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
강의자료6
강의자료6강의자료6
강의자료6
 
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf2.(Sorted list array implementation)This sorted list ADT discussed .pdf
2.(Sorted list array implementation)This sorted list ADT discussed .pdf
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdf
 
Python programming Part -6
Python programming Part -6Python programming Part -6
Python programming Part -6
 
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptxRANDOMISATION-NUMERICAL METHODS  FOR ENGINEERING.pptx
RANDOMISATION-NUMERICAL METHODS FOR ENGINEERING.pptx
 
Underscore.js
Underscore.jsUnderscore.js
Underscore.js
 
ArrayList.docx
ArrayList.docxArrayList.docx
ArrayList.docx
 
Kotlin 101 Workshop
Kotlin 101 WorkshopKotlin 101 Workshop
Kotlin 101 Workshop
 
9 Arrays
9 Arrays9 Arrays
9 Arrays
 
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdfLab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
Lab02kdfshdfgajhdfgajhdfgajhdfgjhadgfasjhdgfjhasdgfjh.pdf
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
 
Introduction of Python-1.pdf
Introduction of Python-1.pdfIntroduction of Python-1.pdf
Introduction of Python-1.pdf
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
collections
collectionscollections
collections
 

Mehr von Vijay Shukla

Mehr von Vijay Shukla (20)

Introduction of webpack 4
Introduction of webpack 4Introduction of webpack 4
Introduction of webpack 4
 
Preview of Groovy 3
Preview of Groovy 3Preview of Groovy 3
Preview of Groovy 3
 
Jython
JythonJython
Jython
 
Groovy closures
Groovy closuresGroovy closures
Groovy closures
 
Grails services
Grails servicesGrails services
Grails services
 
Grails plugin
Grails pluginGrails plugin
Grails plugin
 
Grails domain
Grails domainGrails domain
Grails domain
 
Grails custom tag lib
Grails custom tag libGrails custom tag lib
Grails custom tag lib
 
Grails
GrailsGrails
Grails
 
Gorm
GormGorm
Gorm
 
Controller
ControllerController
Controller
 
Config BuildConfig
Config BuildConfigConfig BuildConfig
Config BuildConfig
 
Command object
Command objectCommand object
Command object
 
Boot strap.groovy
Boot strap.groovyBoot strap.groovy
Boot strap.groovy
 
Vertx
VertxVertx
Vertx
 
Custom plugin
Custom pluginCustom plugin
Custom plugin
 
Spring security
Spring securitySpring security
Spring security
 
REST
RESTREST
REST
 
Config/BuildConfig
Config/BuildConfigConfig/BuildConfig
Config/BuildConfig
 
GORM
GORMGORM
GORM
 

Kürzlich hochgeladen

“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
Muhammad Subhan
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
FIDO Alliance
 

Kürzlich hochgeladen (20)

Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024Extensible Python: Robustness through Addition - PyCon 2024
Extensible Python: Robustness through Addition - PyCon 2024
 
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
Secure Zero Touch enabled Edge compute with Dell NativeEdge via FDO _ Brad at...
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
Choosing the Right FDO Deployment Model for Your Application _ Geoffrey at In...
 
The Metaverse: Are We There Yet?
The  Metaverse:    Are   We  There  Yet?The  Metaverse:    Are   We  There  Yet?
The Metaverse: Are We There Yet?
 
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
ASRock Industrial FDO Solutions in Action for Industrial Edge AI _ Kenny at A...
 
Google I/O Extended 2024 Warsaw
Google I/O Extended 2024 WarsawGoogle I/O Extended 2024 Warsaw
Google I/O Extended 2024 Warsaw
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
Event-Driven Architecture Masterclass: Engineering a Robust, High-performance...
 
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
“Iamnobody89757” Understanding the Mysterious of Digital Identity.pdf
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
Event-Driven Architecture Masterclass: Integrating Distributed Data Stores Ac...
 
Using IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & IrelandUsing IESVE for Room Loads Analysis - UK & Ireland
Using IESVE for Room Loads Analysis - UK & Ireland
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdfHow Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
How Red Hat Uses FDO in Device Lifecycle _ Costin and Vitaliy at Red Hat.pdf
 
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
TrustArc Webinar - Unified Trust Center for Privacy, Security, Compliance, an...
 
WebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM PerformanceWebAssembly is Key to Better LLM Performance
WebAssembly is Key to Better LLM Performance
 
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
Human Expert Website Manual WCAG 2.0 2.1 2.2 Audit - Digital Accessibility Au...
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 

Groovy

  • 2. Agenda 1. Installation 2. Difference with JAVA 3. Groovy Development Kit 4. Syntax 5. Operators 6. Groovy Truth 7. Program Structure (later) 8. Closures
  • 4. Differences with JAVA ● Default Imports ● Multi-Methods ● Array Initializers ● GStrings and String and Character Literals ● Primitives and Wrappers ● Behavior of == ● Extra Keywords
  • 6. Multi-Methods/Runtime-Dispatch In Groovy int method(String arg) { return 1; } int method(Object arg) { return 2; } Object o = "Object"; int result = method(o); assert 1==result In Java int method(String arg) { return 1; } int method(Object arg) { return 2; } Object o = "Object"; int result = method(o); assertEquals(2,result)
  • 8. GStringsand String and Character Literals Singly quoted literals in Groovy are used for Strings, and double quoted result in String as well as GString. ● assert 'c'.getClass()==String ● assert "c".getClass()==String ● assert "c${1}".getClass() in GString When calling methods with argument of type char we need to either cast explicitly or make sure the value has been cast in advance.
  • 9. Groovy Casting can be done by two ways:- ● assert ((char) "c").class==Character ● assert ("c" as char).class==Character For multi char String:- ● assert ((char) 'cx') == 'c' // GroovyCast Exception ● assert ('cx' as char) == 'c' ● assert 'cx'.asType(char) == 'c'
  • 10. Primitive and Wrappers Groovy autowraps references to primitives.
  • 11. Behaviour of == In java == means equality of primitive types or identity for objects. In groovy == translates to a.compareTo(b)==0, if they are comparable and a.equals(b) otherwise. To check Identity we had a.is(b)
  • 12. ● Comments ○ Single Line Comments ○ Multi-line Comments ○ GroovyDoc Comments ● Keywords ○ as ○ def ○ in ○ trait ● Identifier ○ All keywords are also valid identifiers when following a dot. (foo.as) ○ Quoted Identifiers
  • 14. String 1. Single quoted 2. Double quoted 3. Triple Single quoted 4. Triple Double Quoted
  • 15. Operators 1. Arithmetic Operators 2. Relational Operators 3. Logical Operators 4. Conditional Operators 5. Object Operators
  • 16. Elvis Operator(?:) Safe Navigation Operator(?.) Method Pointer Operator (.&) Spread Operator (*.) Range Operator (..) Spaceship Operator (<==>) delegates to compareTo MemberShip Operator (in) User Field Access Operator (.@) http://www.groovy-lang.org/operators.html#_other_operators
  • 17.
  • 18. Groovy Collections Data structure that helps in dealing with a number of objects. A wide variety of methods available for easy manipulation.
  • 19. List A list cares about the index Elements are assigned indices on the basis of how they are added Has methods related to the index Index starts from 0 Creating list //create empty list with each element of type 'def' List list = [ ] //create empty list with elements of type 'type' List<type> list = [ ] List<type> list = new ArrayList()
  • 20. Adding an element list.add(“element1”) list << “element1” list += “element1” list.push(element) List firstList = [1,2,3,4,5] List secondList = [“element2”] List thirdList = firstList + secondList println thirdList // [1,2,3,4,5,”element2”] fourthlist = thirdlist - firstlist println fourthlist // [“element2”]
  • 21. Fetching elements: list[i] – Get ith element in list starting from 0 list.get(0) – Get first element in list list.getAt(0) – Get first element in list list.first() - Get first element of list list.head() - Get the head of list list.last() - Get last element of list list.tail() - Get all elements except first list.getAt(1..10) – Get elements from index 1 to 10 (includes index 10) list.subList(1, 10) - Get elements at index 1 to 10 (index 10 excluded)
  • 22. Removing duplicates from a List : list.unique() // Alters original list list as Set Deleting an element from a List : (All of them alter original list) list.remove(idx) list.pop() list.removeAll(collection)
  • 23. Convert String into List: “Hi” as List / “Hi”.toList() string.tokenize('_') : Splits the string into a list with argument used as delimiter. string.split('_') : Same as tokenize but can also accept regular expressions as delimiters Convert List into String: list.join(',')
  • 24. Operations on each element of list: println list*.name // Use of spread operator list.collect { it.multiply(2) } // what if 'it' refers to string? list.find { it.name==”abc” } // returns one object list.findAll { it.name==”abc” } // returns list list.each { println it.name } list.eachWithIndex{p, index -> println index +”. “ + p.name } list.reverseEach { println it.name }
  • 25. List Methods size() - Get size of list reverse() - reverses the order of list elements contains(value) – Find if list contains specified value sum(closure) - Sum all the elements of the list min(closure) – Get min value of list max(closure) – Get max value of list flatten() - Make nested lists into a simple list sort(closure) - Sort the list in ascending order
  • 26. .list1.intersect(list2) : returns a list that contains elements that exist in both the lists. .list1.disjoint(list2) : Returns true/false indicating whether lists are disjoint or not. .every{condition} : checks whether every element of the list satisfy the condition. .any{condition} : checks whether any of the element of the satisfy the condition.
  • 27. Set A Set cares about uniqueness - it doesn't allow duplicates It can be considered as a list with restrictions, and is often constructed from a list. Set set = [1,3,3,4] as Set ([1,3,4]) No Ordering; element positions do not matter
  • 28. Most methods available to lists, besides those that don't make sense for unordered items, are available to sets. Like - getAt, putAt, reverse
  • 29. Ranges Ranges allow you to create a list of sequential values. These can be used as Lists since Range extends java.util.List. Generally used for looping, switch, lists etc Ranges defined with the “..” notation are inclusive (that is the list contains the from and to value). Ranges defined with the “..<” notation are exclusive, they include the first value but not the last value.
  • 30. Range range = 1..10 range = -10..<10 range = '#'..'~' Methods range.from – Get the lower limit of range range.to – Get upper limit of range range.contains(value) – Does range contain value?
  • 31. 1. Groovy Truth (later) 2. Program Structure (later) 3. Closures(later)