Groovy - in operator
in operator provides an elegant and concise way to check membership or containment of an item in a Groovy data structures or ranges.
Checking Membership in Groovy Collections
We can check if a value is present in a collection like List or Set easily using in operator.
Example.groovy
def numbers = [1, 2, 3, 4, 5]
def numberToSearch = 3
if (numberToSearch in numbers) {
println "$numberToSearch is present in the list"
}else {
println "$numberToSearch is not present in the list"
}
def letters = ['a', 'b', 'c']
if ('f' in letters) {
println "f is in the list"
} else {
println "f is not in the list"
}
def mySet = [10, 20, 30] as Set
if (20 in mySet) {
println "20 is present in the set"
} else {
println "20 is not present in the set"
}
Output
When we run the above program, we will get the following result.
3 is present in the list f is not in the list 20 is present in the set
Checking Value in Groovy Ranges
We can check if a value lies between given range using in operator as shown below. in operator checks the value on left hand side in the given range on right hand size.
Example.groovy
def myRange = 1..10
def value = 7
if (value in myRange) {
println "$value is within the range 1 to 10."
}else{
println "$value is out of range."
}
if (15 in 1..5) {
println "15 is in the range 1 to 5."
} else {
println "15 is out of rangd."
}
def charRange = 'a'..'f'
if ('c' in charRange) {
println "c is in the character range a to f"
}else{
println "c is out of range"
}
Output
When we run the above program, we will get the following result.
7 is within the range 1 to 10. 15 is out of rangd. c is in the character range a to f
Checking a key in a Map
We can check if a key is present in the Map or not.
Example.groovy
def map = ['name': 'Julie', 'age': 30, 'city': 'Delhi']
if ('age' in map) {
println "The map contains a key 'age'"
} else {
println "The map is not having key 'age'"
}
if ('country' in map) {
println "The map contains a key 'country'"
} else {
println "The map is not having key 'country'"
}
Output
When we run the above program, we will get the following result.
7 is within the range 1 to 10. 15 is out of rangd. c is in the character range a to f
Advertisements