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)  

Membership operator Groovy

Share:
263,470
banderson623
Author by

banderson623

I like to program javascript, ruby, c and groovy

Updated on June 24, 2020

Comments

  • banderson623
    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 as true.

    • Atharva Johri
      Atharva Johri about 12 years
      Can you find the index out also of where this equal element is in the list?
    • Thomas Traude
      Thomas Traude about 12 years
      @AtharvaJohri assert [12,42,33].indexOf(42) == 1
  • Harshay Buradkar
    Harshay Buradkar over 11 years
    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'.
  • Automatico
    Automatico over 9 years
    @HarshayBuradkar To make really sure true == true, of course #joke
  • Jesse Glick
    Jesse Glick over 7 years
    Careful. def m = [a: true]; 'a' in m → true yet def m = [a: false]; 'a' in m → false!
  • Naeel Maqsudov
    Naeel Maqsudov over 6 years
    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).
  • Big McLargeHuge
    Big McLargeHuge almost 4 years
    How do you negate this?
  • Leponzo
    Leponzo over 2 years
    @BigMcLargeHuge !(1 in [1,2,3])
  • Gaurav
    Gaurav over 2 years
    works flawlessly!
  • wiredniko
    wiredniko about 2 years
    The way to deal with [a:false] is to use contains. [a: false].containsKey('a') -> true