Groovy - Map putAt(Object key, Object value) method
Description
Groovy Map putAt(Object key, Object value) method allows to use subscript operator to be used in a Map.
Syntax
public Object putAt(Object key, Object value)
Parameters
key − Object as key of the Map
value − Object as value of the Map
Return Value
Current map with entries of collection passed.
Example - Adding entry to a Map of String and String
Following is an example of the usage of this method −
main.groovy
// define a map
def map = ["A" : "Apple", "B" : "Banana"]
// add entry to the map
map.putAt("C","Carrot")
// add entry using subscript operator
map["G"] = "Grapes"
println(map)
Output
When we run the above program, we will get the following result −
[A:Apple, B:Banana, C:Carrot, G:Grapes]
Example - Adding entry to a Map of Integer and Integer
Following is an example of the usage of this method −
main.groovy
// define map def map = [1 : 11, 2 : 12] // add entry to the map map.putAt(3,13) // add entry using subscript operator map[4] = 14 println(map)
Output
When we run the above program, we will get the following result −
[1:11, 2:12, 3:13, 4:14]
Example - Adding entry to a Map of Integer and Object
Following is an example of the usage of this method −
main.groovy
// define maps
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert")]
// add entry to the map
map.putAt(3,new Student(3, "Markus"))
// add entry using subscript operator
map[4] = new Student(4, "Adam")
println(map)
class Student{
int rollNo
String name
Student(int rollNo, String name){
this.rollNo = rollNo
this.name = name
}
@Override
public boolean equals(Object obj) {
Student s = (Student)obj
return this.rollNo == s.rollNo && this.name.equalsIgnoreCase(s.name)
}
@Override
public String toString() {
return "[ " + this.rollNo + ", " + this.name + " ]"
}
}
Output
When we run the above program, we will get the following result −
[1:[ 1, Julie ], 2:[ 2, Robert ], 3:[ 3, Markus ], 4:[ 4, Adam ]]
groovy_maps.htm
Advertisements