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
.

- 81,889
- 28
- 189
- 210

- 2,708
- 2
- 19
- 13
-
Can you find the index out also of where this equal element is in the list? – Arturo Mar 30 '12 at 11:53
-
2@AtharvaJohri `assert [12,42,33].indexOf(42) == 1` – Thomas Traude Mar 30 '12 at 19:09
8 Answers
Some syntax sugar
1 in [1,2,3]

- 63,927
- 12
- 112
- 147

- 3,013
- 2
- 15
- 5
-
40Careful. `def m = [a: true]; 'a' in m` → true yet `def m = [a: false]; 'a' in m` → false! – Jesse Glick Feb 01 '17 at 19:15
-
-
-
3The way to deal with `[a:false]` is to use contains. `[a: false].containsKey('a')` -> true – wiredniko Apr 12 '22 at 13:52
-
@Big McLargeHuge negation is also possible like this: `1 !in [1,2,3]` ([Membership operator Groovy](https://docs.groovy-lang.org/latest/html/documentation/#_membership_operator)) – david Aug 21 '23 at 10:32
.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')

- 5,318
- 4
- 28
- 37
-
And, 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)`. – Naeel Maqsudov Dec 18 '17 at 12:58
For lists, use contains
:
[1,2,3].contains(1) == true

- 11,929
- 4
- 44
- 74

- 2,708
- 2
- 19
- 13
-
21Probably 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'. – Harshay Buradkar Nov 30 '12 at 03:01
-
6@HarshayBuradkar To make really sure `true == true`, of course #joke – Automatico Jan 20 '15 at 10:29
You can use Membership operator:
def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)

- 19,198
- 2
- 29
- 30
If you really want your includes method on an ArrayList, just add it:
ArrayList.metaClass.includes = { i -> i in delegate }

- 2,338
- 1
- 17
- 20
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.

- 637
- 7
- 15
def fruitBag = ["orange","banana","coconut"]
def fruit = fruitBag.collect{item -> item.contains('n')}
I did it like this so it works if someone is looking for it.

- 21,252
- 9
- 60
- 109

- 31
- 1
You can also use matches with regular expression like this:
boolean bool = List.matches("(?i).*SOME STRING HERE.*")

- 3,342
- 2
- 16
- 33

- 23
- 1
- 7