155

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.

Opal
  • 81,889
  • 28
  • 189
  • 210
banderson623
  • 2,708
  • 2
  • 19
  • 13

8 Answers8

282

Some syntax sugar

1 in [1,2,3]
Mads Hansen
  • 63,927
  • 12
  • 112
  • 147
dahernan
  • 3,013
  • 2
  • 15
  • 5
158

.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')
shemnon
  • 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
69

For lists, use contains:

[1,2,3].contains(1) == true
Alex Gyoshev
  • 11,929
  • 4
  • 44
  • 74
banderson623
  • 2,708
  • 2
  • 19
  • 13
  • 21
    Probably 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
10

You can use Membership operator:

def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)  

Membership operator Groovy

MagGGG
  • 19,198
  • 2
  • 29
  • 30
8

If you really want your includes method on an ArrayList, just add it:

ArrayList.metaClass.includes = { i -> i in delegate }
John Flinchbaugh
  • 2,338
  • 1
  • 17
  • 20
3

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.

Twelve24
  • 637
  • 7
  • 15
2
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.

Petter Friberg
  • 21,252
  • 9
  • 60
  • 109
HinataXV
  • 31
  • 1
0

You can also use matches with regular expression like this:

boolean bool = List.matches("(?i).*SOME STRING HERE.*")
Pedro Fracassi
  • 3,342
  • 2
  • 16
  • 33
ninj
  • 23
  • 1
  • 7