Reputation: 1207
I want to check if any of curently logged in user roles are in specific list of roles. But it can be any two collection.
Basically I want to check if any memeber of [x1,x3,x4] collection is contained in [x2,x3,x7]
How to do this in Groovy (Grails)?
Upvotes: 1
Views: 913
Reputation: 1
def a = [1,2,3]
def b = [3,4,5]
def result = false
a.each{it->
if(b.contains(it))
result =true
}
return result
Upvotes: 0
Reputation: 19229
You can use the Collection#disjoint
method:
def a = [5, 4, 3]
def b = [7, 6, 5]
// a contains a member of b if they are not disjoint.
assert !a.disjoint(b)
assert a.disjoint([8, 7, 6])
Other alternatives are !a.intersect(b).empty
or a.any { it in b }
but i think the disjoint
solution is the most direct one and (wild speculation here) probably the most performant one as it doesn't need intermediate collections or closures (update: well, the code for disjoint
reveals that it does some some funky stuff under the hood... but then again nearly all Groovy methods do =P).
Upvotes: 4
Reputation: 577
boolean check(Collection c1, Collection c2) {
for(def i in c1) {
if(c2.contains(i)) {
return true
break
}
}
return false
}
Upvotes: 0