How to check if element in groovy array/hash/collection/list?

ArraysListGroovy

Arrays Problem Overview


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.

Arrays Solutions


Solution 1 - Arrays

Some syntax sugar

1 in [1,2,3]

Solution 2 - Arrays

.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 3 - Arrays

For lists, use contains:

[1,2,3].contains(1) == true

Solution 4 - Arrays

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

ArrayList.metaClass.includes = { i -> i in delegate }

Solution 5 - Arrays

You can use Membership operator:

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

Membership operator Groovy

Solution 6 - Arrays

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.

Solution 7 - Arrays

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.

Solution 8 - Arrays

You can also use matches with regular expression like this:

boolean bool = List.matches("(?i).*SOME STRING HERE.*")

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionbanderson623View Question on Stackoverflow
Solution 1 - ArraysdahernanView Answer on Stackoverflow
Solution 2 - ArraysshemnonView Answer on Stackoverflow
Solution 3 - Arraysbanderson623View Answer on Stackoverflow
Solution 4 - ArraysJohn FlinchbaughView Answer on Stackoverflow
Solution 5 - ArraysMagGGGView Answer on Stackoverflow
Solution 6 - ArraysTwelve24View Answer on Stackoverflow
Solution 7 - ArraysHinataXVView Answer on Stackoverflow
Solution 8 - ArraysninjView Answer on Stackoverflow