Groovy tutorial with examples
Map
Groovy has native language supports for java.util.Map, In addition Groovy has some Special syntax for map literals, and additional common methods. In this page we shows some additional common method of Groovy Map.
You can define an empty Map as
def map = [:]
and you can assign value as
You can use each() and eachWithIndex() to access keys and values:
def str= new StringBuffer() map.each{ str << it.key +':'+ it.value +', '} println str.toString()
You can check the contents of a map with various methods:
println [:].isEmpty() // true println map.isEmpty() // false println map.containsKey(2) // true println map.containsValue('b') // true println map.containsValue('z') // false // clear map.clear() println map // group a list into a map using some criteria def map2 =[1:'a', 7:'b', 6:'b', 3:'c'] println map2.groupBy{ it.key } println map2.groupBy{ it.value }
How to iterate List inside another List in groovy
package com.java.connect.groovy class GroovyListEachExample { static void main(args){ def list1 = ['Window', 'Linux', 'Mac'] def list2 = [ 'java', 'C', 'C++', '.Net', 'PHP', 'Testing' ] list1.each {platform-> list2.each {language-> println "Learning $language on $platform OS." } println "----------------------------------" } } } //output Learning java on Window OS. Learning C on Window OS. Learning C++ on Window OS. Learning .Net on Window OS. Learning PHP on Window OS. Learning Testing on Window OS. ---------------------------------- Learning java on Linux OS. Learning C on Linux OS. Learning C++ on Linux OS. Learning .Net on Linux OS. Learning PHP on Linux OS. Learning Testing on Linux OS. ---------------------------------- Learning java on Mac OS. Learning C on Mac OS. Learning C++ on Mac OS. Learning .Net on Mac OS. Learning PHP on Mac OS. Learning Testing on Mac OS. ----------------------------------
List
Groovy has native language support for lists, You can use all the methods of java.util.List for Groovy list, in addition groovy provides special syntax for list literals and additional common methods which you can use for Groovy List. You also can do Operator overloading on Groovy List.
//create a new list def emptyList = [] def list = [1, 2, 3, 4, 5, 6] println emptyList.size() // This will give 0 println list.size() // This will give 6 You can add other list by ‘+’ operator. // You can add other list by '+' operator list = list + [7, 8] println list // Gives as [1, 2, 3, 4, 5, 6, 7, 8] //As well you can minus some elements by ‘-‘ operator. list = list - [1] println list // Gives as [2, 3, 4, 5, 6, 7, 8] //add more elements into list by ‘<<' operator. list = list << 9 println list // Gives as [2, 3, 4, 5, 6, 7, 8, 9] //You can multiply the list by ‘*’ operator. The ‘*’ operator will repeat the list by given times. list = list*2 // or list.multiply(2) println list // Gives as [2, 3, 4, 5, 6, 7, 8, 9, 2, 3, 4, 5, 6, 7, 8, 9] //make a flat list of elements assert [1, 2, [3, 4]].flatten() == [1, 2, 3, 4] //You can reverse the list using reverse() method def list1 = [1, 2, 3, 4] list1 = list1.reverse() println list1 // Gives as [4, 3, 2, 1] //You can get the number of unique elements in list. def list1 = [1, 2, 3, 4, 2] list1 = list1.unique() println list1 // Gives as [1, 2, 3, 4] //You can sort the elements of list. def list1 = [2, 2, 1, 4, 3] list1 = list1.sort() println list1 // Gives as [1, 2, 2, 3, 4] //You can search the elements or collect the list of elements using find or findAll method as below. def list1 = [2, 2, 1, 4, 3] list1 = list1.find{it ==1} println list1 // Gives as 1 //Or def list1 = [2, 2, 1, 4, 3] list1 = list1.findAll{it >1} println list1 // Gives as [2, 2, 4, 3] //You can iterate elements of list using ‘each’ method. def list1 = [2, 2, 1, 4, 3] list1 = list1.each { println it }
Dates
The Groovy supports mostly same as Java, It uses the java.util.Date or java.util.Calendar to get the Date object. Or some time it can use the java.sql.Date to bulid the Date object, as you must know we no need to explicitly import the Date object in Groovy, So Groovy creates the Date object for us.
Date date = new Date() //Groovy also can make use of third party java date library like Joda. //Groovy has the special support for changing time like this. Date date = new Date() println(date) use(TimeCategory) { Date date2 = date + 1.week + 6.hours println(date2) } // full code import static java.util.Calendar.getInstance as now import groovy.time.TimeCategory import java.text.SimpleDateFormat class GroovyDateExample { static void main(def args) { // get the current time println("Current time is "+now().time) // You can add the number of days in date like this def date1 = new Date() + 1 println("Tomorrow’s 's date " +date1) //Get the date Date date = new Date() println(date) use(TimeCategory) { Date date2 = date + 1.week + 6.hours println("Date after adding 1 week and 6 hours is "+date2) } def input = "12-12-1981" def df1 = new SimpleDateFormat("dd-MM-yyyy") def date3 = df1.parse(input) def df2 = new SimpleDateFormat("MMM/dd/yyyy") println('The Original date was ' + df2.format(date3)) } } //output Current time is Sun Jul 10 11:30:13 GMT 2021 Tomorrow’s date Mon Jul 11 11:30:13 GMT 2021 Sun Jul 10 11:30:13 GMT 2021 Date after adding 1 week and 6 hours is Sun Jul 17 17:30:13 GMT 2021 The Original date was Dec/12/1981
Numbers
Java supports primitive types and object types for all numbers types of java. Java has the wrapper classes to allow conversion from primitives to object or object to primitive. Java 5+ has the autoboxing feature to hide the conversion.
Groovy treats everything as an object at the language level and it does appropriate autoboxing under the cover when integrating with java.
BigDecimal used as the default type for non-Integers in Groovy, the operator overloading applies to all common operations on numbers, e.g. 4 * 5 is the same as 4.multiply(5)
You can use these operators for your own types, e.g. Person * 3 calls the multiple method on your person object.
class GroovyNumberExample { static void main(def args) { def x = 5 def y = 6 // You can do normal add println(x + y) // This is also allowed println(x.plus(y)) // You can check the x in what instance println(x instanceof Integer) // Take the other example def a = 5/6 // Get round value def b = a.setScale(4, BigDecimal.ROUND_HALF_UP) println(b.toString()) // Add by operator println(7+8) // Add by method println(7.plus(7)) // Minus by operator println(7-6) // Minus by method println(7.minus(6)) // Multiply by operator println(4*12) // Multiply by method println(4.multiply(12)) // mod by operator println(45%35) // mod by method println(45.mod(35)) // Power by operator println(4**2) //Power by method println(4.power(2)) //Division by operator println(4/3) // Division by method println(4.div(3)) // Normal integer division println(4.intdiv(3)) } }
String
Single quotes string
You can define the String in single quotes in Groovy, These string are simple string below is the example code defining string in single quotes.
class GroovyStringExample { static void main(def args){ // Single quotes string def name = 'Sam' def lastname = 'Crow' println name + ' ' + lastname // Double quotes string with variables evaluations def text = " My full name is $name $lastname" println(text) // You can get by indexing indexing assert fullname[0..7] == name assert fullname[-4..-1] == lastname // Multi-line strings def sentance = '''\ This is line 1, This is line 2''' def lines =sentance.split('\n') assert lines.size() == 2 // substrings example def string = 'My name is spiderman' string = string-'name'-'is' - 'My' + ' gone' println(string) // Replacement println(string.replace('gone','back')) //You can process the each chars of the String in Groovy, There are different way to do this, below is the example of some of char processing. // You can process characters as well assert 'spiderman'.toList() == [ 's', 'p', 'i', 'd', 'e', 'r', 'm', 'a', 'n' ] //You also can do like this and process the each char inside string 'spiderman' as String[] 'spiderman'.split('') 'spiderman'.each{} string = "spiderman is back" println(string.toList().unique().sort().join()) } }