How do I figure out if an array contains an element?
I thought there might be something like [1, 2, 3].includes(1) which would evaluate as true.
8 Answers
Some syntactic sugar
1 in [1,2,3]
6 Comments
def m = [a: true]; 'a' in m → true yet def m = [a: false]; 'a' in m → false!!(1 in [1,2,3])[a:false] is to use contains. [a: false].containsKey('a') -> true1 !in [1,2,3] (Membership operator Groovy).contains() is the best method for lists, but for maps you will need to use .containsKey() or .containsValue()
[a:1,b:2,c:3].containsValue(3)
[a:1,b:2,c:3].containsKey('a')
1 Comment
if(aMap["aKey"]==aValue).For lists, use contains():
[1,2,3].contains(1) == true
2 Comments
true == true, of course #jokeYou can use Membership operator:
def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)
Comments
IMPORTANT Gotcha for using .contains() on a Collection of Objects, such as Domains. If the Domain declaration contains a EqualsAndHashCode, or some other equals() implementation to determine if those Ojbects are equal, and you've set it like this...
import groovy.transform.EqualsAndHashCode
@EqualsAndHashCode(includes = "settingNameId, value")
then the .contains(myObjectToCompareTo) will evaluate the data in myObjectToCompareTo with the data for each Object instance in the Collection. So, if your equals method isn't up to snuff, as mine was not, you might see unexpected results.
Comments
You can also use matches with regular expression like this:
boolean bool = List.matches("(?i).*SOME STRING HERE.*")
assert [12,42,33].indexOf(42) == 1