Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check in Groovy that object is a list or collection or array?

The question is as simple as the title. How to check in Groovy that object is a list or collection or array? But can't find a simple way of checking it. Any ideas?

like image 639
Andrey Adamovich Avatar asked Sep 01 '11 18:09

Andrey Adamovich


People also ask

How do I know the type of a variable in Groovy?

You can use the getClass() method to determine the class of an object. Also, if you want to check if an object implements an Interface or Class, you can use the instanceof keyword. That's it about checking the datatype of an object in Groovy.

How do you check if an element is present in an array in Groovy?

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

What is a collection in Groovy?

3.3 Iteration Groovy Collection interface defines looping methods: collect() – iterates through the collection transforming each element into new value with Closure. IDENTITY. collect(Closure transform) – iterates through the collection transforming each element into new value using closure.

How do I read an array in Groovy?

In Groovy, you can access array item by using square bracket with an index ( [index] ) or using getAt(index) function.


3 Answers

A List is a Collection, so the checks aren't mutually exclusive:

def foo = ... boolean isCollection = foo instanceof Collection boolean isList = foo instanceof List boolean isSet = foo instanceof Set boolean isArray = foo != null && foo.getClass().isArray() 
like image 91
Burt Beckwith Avatar answered Sep 23 '22 03:09

Burt Beckwith


I don't know if you need to distinguish between Collection, List and Array, or just want to know if an object is any of these types. If the latter, you could use this:

boolean isCollectionOrArray(object) {    
    [Collection, Object[]].any { it.isAssignableFrom(object.getClass()) }
}

// some tests
assert isCollectionOrArray([])
assert isCollectionOrArray([] as Set)
assert isCollectionOrArray([].toArray())
assert !isCollectionOrArray("str")

Run the code above in the Groovy console to confirm it behaves as advertised

like image 41
Dónal Avatar answered Sep 25 '22 03:09

Dónal


If you are looking for a Groovy way, look at in operator. It is actually a combination of Class.isAssignableFrom(Class<?>) and Class.isInstance(Object) meaning that you can use it to test classes as well as objects.

// Test classes
assert ArrayList in Collection
assert ArrayList in List
assert HashSet in Collection
assert HashSet in Set

// Test objects
def list = [] as ArrayList
def set = [] as HashSet

assert list in Collection
assert list in List
assert set in Collection
assert set in Set

Testing if an object is an array may be tricky. I would recommend @BurtBeckwith's approach.

def array = [].toArray()

assert array.getClass().isArray()
like image 37
pgiecek Avatar answered Sep 24 '22 03:09

pgiecek