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

51,425

Solution 1

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

Solution 2

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()

Solution 3

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()

Solution 4

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

Solution 5

Usually you'd want to check its behavior with duck typing.

def foo = someMethod()
if (foo.metaClass.respondsTo('each')) {
  foo.each {println it}
}
Share:
51,425
Andrey Adamovich
Author by

Andrey Adamovich

A software craftsman with many years of experience in different lifecycle phases of software creation. He is passionate about defining good development practices, documenting and presenting architecture, reuse of code and design patterns, profiling and analysis of application performance as well as extreme automation of development and operations activities. At the moment, Andrey is working as a free-lance DevOps consultant offering his expertise in implementing DevOps initiatives, selecting automation tooling, switching to infrastructure-as-code and immutable infrastructure and constructing software delivery pipelines. Another Andrey's passion is teaching software automation practices and tooling. His DevOps MasterClass (eXtreme Automation) course has been delivered more than 20 times in various locations in Europe: Austria, Sweden, Denmark, UK, Romania, Estonia, Latvia. Andrey is also a co-founder of DevChampions training center. Andrey is a frequent speaker at international conferences and local communities. He is one of the leaders of LatCraft - Latvian Software Craftsmanship Community as well as co-founder and organizer of DevTernity conference.

Updated on April 02, 2020

Comments

  • Andrey Adamovich
    Andrey Adamovich about 4 years

    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?