Groovy - Map asBoolean() method
Description
Groovy Map asBoolean() method coerces the map to boolean value. For empty map, it returns false and for non-empty map, it returns true.
Syntax
public boolean asBoolean()
Parameters
NA
Return Value
false if map is empty else true.
Example - Coercing 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", "C": "Carrot"] // coerce map println(map.asBoolean()) // set map as empty map = [:] // coerce map println(map.asBoolean())
Output
When we run the above program, we will get the following result −
true false
Example - Coercing Map of Integer and Integer
Following is an example of the usage of this method −
main.groovy
// define a map def map = [1 : 11, 2 : 12, 3: 6] // coerce map println(map.asBoolean()) // set map as empty map = [:] // coerce map println(map.asBoolean())
Output
When we run the above program, we will get the following result −
true false
Example - Checking entries of 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")]
// coerce map
println(map.asBoolean())
// set map as empty
map = [:]
// coerce map
println(map.asBoolean())
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 −
true false
groovy_maps.htm
Advertisements