Groovy - Lists contains() Returns true if this List contains the specified value.
In Groovy, you can access array item by using square bracket with an index ( [index] ) or using getAt(index) function.
The List is a structure used to store a collection of data items. In Groovy, the List holds a sequence of object references. Object references in a List occupy a position in the sequence and are distinguished by an integer index.
Arrays. An Array is an object that contains elements of similar data type. Groovy reuses the list notation for arrays, but to make such literals arrays, you need to explicitly define the type of the array through coercion or type declaration. You can also create multi-dimensional arrays.
Some syntax sugar
1 in [1,2,3]
.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')
For lists, use contains
:
[1,2,3].contains(1) == true
If you really want your includes method on an ArrayList, just add it:
ArrayList.metaClass.includes = { i -> i in delegate }
You can use Membership operator:
def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)
Membership operator Groovy
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With