Groovy - Map put(Object key, Object value) method
Description
Groovy Map put(Object key, Object value) method associates the specified value with the specified key in this Map. If this Map previously contained a mapping for this key, the old value is replaced by the specified value.
Syntax
public Object put(Object key, Object value)
Parameters
key − The key to be put in the map.
value − The associated value for the key.
Return Value
The returned key-value pair which is inserted.
Example - Adding key-value pair to a Map of String and String
Following is an example of the usage of this method −
main.groovy
// define a map
def map = ["TopicName" : "Maps", "TopicDescription" : "Methods in Maps"]
// add a new key-value pair
map.put("TopicID","1");
println(map);
Output
When we run the above program, we will get the following result −
[TopicName:Maps, TopicDescription:Methods in Maps, TopicID:1]
Example - Adding key-value pair to a Map of Integer and String
Following is an example of the usage of this method −
main.groovy
// define a map def map = [1 : "Apple", 2 : "Banana"] // add a new key-value pair map.put(3,"Mango"); println(map);
Output
When we run the above program, we will get the following result −
[1:Apple, 2:Banana, 3:Mango]
Example - Adding key-value pair to a Map of Integer and Object
Following is an example of the usage of this method −
main.groovy
// define a map
def map = [1 : new Student(1, "Julie"), 2 : new Student(2, "Robert")]
// add a new key-value pair
map.put(3,new Student(3, "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, Adam ]]
groovy_maps.htm
Advertisements