Groovy provides below ways to add elements to the map.
a.
Using put method
b.
Using putAll method
c.
Using subscript operator
Using put method
HelloWorld.groovy
def countryCapitals = ["India" : "new Delhi", "Australia" : "Canberra"] printMap(countryCapitals) println "\nAdding two more country details\n" countryCapitals.put('Colombia', 'Bogota') countryCapitals.put('Libya', 'Tripoli') printMap(countryCapitals) void printMap(map){ map.eachWithIndex {entry, i -> println "$i : CountryName: $entry.key, Capital: $entry.value" } }
Output
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra
Adding two more country details
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra
2 : CountryName: Colombia, Capital: Bogota
3 : CountryName: Libya, Capital: Tripoli
Using putAll method
putAll method used to copy the elements from one map to
this map.
HelloWorld.groovy
def countryCapitals = ["India" : "new Delhi", "Australia" : "Canberra"] def tempCountries = ['Colombia' : 'Bogota', 'Libya':'Tripoli'] printMap(countryCapitals) println "\nAdding two more country details\n" countryCapitals.putAll(tempCountries) printMap(countryCapitals) void printMap(map){ map.eachWithIndex {entry, i -> println "$i : CountryName: $entry.key, Capital: $entry.value" } }
Output
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra
Adding two more country details
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra
2 : CountryName: Colombia, Capital: Bogota
3 : CountryName: Libya, Capital: Tripoli
Using subscript operator
countryCapitals['Colombia'] = 'Bogota'
countryCapitals['Libya'] = 'Tripoli'
HelloWorld.groovy
def countryCapitals = ["India" : "new Delhi", "Australia" : "Canberra"] printMap(countryCapitals) println "\nAdding two more country details\n" countryCapitals['Colombia'] = 'Bogota' countryCapitals['Libya'] = 'Tripoli' printMap(countryCapitals) void printMap(map){ map.eachWithIndex {entry, i -> println "$i : CountryName: $entry.key, Capital: $entry.value" } }
Output
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra
Adding two more country details
0 : CountryName: India, Capital: new Delhi
1 : CountryName: Australia, Capital: Canberra
2 : CountryName: Colombia, Capital: Bogota
3 : CountryName: Libya, Capital: Tripoli
No comments:
Post a Comment