There are three ways to check whether an element exit in
the list or not.
a.
Using in operator
b.
Using contains method
c.
Using containsAll method
Using in operator
HelloWorld.groovy
primes = [2, 3, 5, 7, 11, 13] is2Exist = 2 in primes is17Exist = 17 in primes is7Exist = 7 in primes println "is2Exist : $is2Exist" println "is17Exist : $is17Exist" println "is7Exist : $is7Exist"
Output
is2Exist : true
is17Exist : false
is7Exist : true
Using contains method
public boolean contains(Object item)
Returns true if this iterable contains the item.
HelloWorld.groovy
primes = [2, 3, 5, 7, 11, 13] is2Exist = primes.contains(2) is17Exist = primes.contains(17) is7Exist = primes.contains(7) println "is2Exist : $is2Exist" println "is17Exist : $is17Exist" println "is7Exist : $is7Exist"
Output
is2Exist : true
is17Exist : false
is7Exist : true
Using containsAll
method
HelloWorld.groovy
primes = [2, 3, 5, 7, 11, 13] isExist = primes.containsAll([2, 7, 13]) println "Is [2, 7, 13] exist in $primes : $isExist" isExist = primes.containsAll([2, 7, 13, 19]) println "Is [2, 7, 13, 19] exist in $primes : $isExist"
Output
Is [2, 7, 13] exist in [2, 3, 5, 7, 11, 13] : true
Is [2, 7, 13, 19] exist in [2, 3, 5, 7, 11, 13] : false
No comments:
Post a Comment