How to check in Groovy that object is a list or collection or array?
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()
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()
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
I use this to "arrayfy" an object, if its already a collection then it will return a copy, else wrap it in a list. So you don't need to check it while processing, it will be always a collection.
def arrayfy = {[] + it ?: [it]}
def list = arrayfy(object) // will be always a list