Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy not in collection

Tags:

groovy

The groovy way to see if something is in a list is to use "in"

   if('b' in ['a','b','c']) 

However how do you nicely see if something is not in a collection?

  if(!('g' in ['a','b','c'])) 

Seems messy and the "!" is hidden to the casual glance. Is there a more idiomatic groovy way to do this?

Thanks!

like image 952
Bob Herrmann Avatar asked Dec 14 '11 02:12

Bob Herrmann


People also ask

How do you check if a value is in a list Groovy?

Groovy - Lists contains() Returns true if this List contains the specified value.

How does Groovy collect work?

The collect() method in Groovy can be used to iterate over collections and transform each element of the collection. The transformation is defined in as a closure and is passed to the collect() method. But we can also add an initial collection to which the transformed elements are added.

How do I use contains in Groovy?

Groovy - contains()Checks if a range contains a specific value.

How do I declare an array variable in Groovy?

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.


Video Answer


1 Answers

Another way to write it is with contains, e.g.

if (!['a', 'b', 'c'].contains('b')) 

It saves the extra level of parentheses at the cost of replacing the operator with a method call.

like image 198
ataylor Avatar answered Oct 07 '22 07:10

ataylor