How to check if element in groovy array/hash/collection/list?
263,470
Solution 1
.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')
Solution 2
Some syntax sugar
1 in [1,2,3]
Solution 3
For lists, use contains
:
[1,2,3].contains(1) == true
Solution 4
If you really want your includes method on an ArrayList, just add it:
ArrayList.metaClass.includes = { i -> i in delegate }
Solution 5
You can use Membership operator:
def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)
Comments
-
banderson623 about 4 years
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 astrue
.-
Atharva Johri about 12 yearsCan you find the index out also of where this equal element is in the list?
-
Thomas Traude about 12 years@AtharvaJohri
assert [12,42,33].indexOf(42) == 1
-
-
Harshay Buradkar over 11 yearsProbably you wanted to say [1,2,3].contains(1). Because I am guessing contains function itself already returns a boolean. Why do you want to again compare it with a hardcoded 'true'.
-
Automatico over 9 years@HarshayBuradkar To make really sure
true == true
, of course #joke -
Jesse Glick over 7 yearsCareful.
def m = [a: true]; 'a' in m
→ true yetdef m = [a: false]; 'a' in m
→ false! -
Naeel Maqsudov over 6 yearsAnd, in addition, to check if a map contains some not null value under a certain key, it is enough to check the following expression
if(aMap["aKey"]==aValue)
. -
Big McLargeHuge almost 4 yearsHow do you negate this?
-
Leponzo over 2 years@BigMcLargeHuge
!(1 in [1,2,3])
-
Gaurav over 2 yearsworks flawlessly!
-
wiredniko about 2 yearsThe way to deal with
[a:false]
is to use contains.[a: false].containsKey('a')
-> true