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?
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.
Groovy - Lists contains() Returns true if this List contains the specified value.
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.
In Groovy, you can access array item by using square bracket with an index ( [index] ) or using getAt(index) function.
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()
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
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()
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