The Groovy spread operator * (asterisk)

Whenever it comes to operating on collections, you know why you’ll love Groovy.
In this example we’ll get to know the asterisk or spread operator, a really helpful colleague – and believe me, it’s got nothing to do with pointers from C ;-) !

Actually, the operator has two functions:

  • Firstly, it’s used to spread or “explode” lists. So it’s actually the counterpart of a join operation
  • Secondly it provides an even shorter way of traversing and operating collections.

Let’s have a look on the first use case and assume we’ve two lists that we’d like to merge. Using the spread operator, it’s a one-liner:

def list0ne = ['a','b']
def listTwo = ['c','d']
def listAll = [*list0ne, *listTwo]

assert listAll.equals(['a','b','c','d'])

def otherList = []
otherList.addAll(listOne)
otherList.addAll(listTwo)
assert listAll.equals(otherList)

So listAll is created by “exploding” the lists first and packing their elements into the new list. A more Java-like way to achieve the same is shown using the addAll method.

The second use case of the spread operator refers to calling an object’s methods on each item of a collection. Note that the method called cannot be an arbitrary method but must be one known to the object.
For example to get the hashCodes of strings, one could use this statement:

def strings = ["1","2","3"]
def hashCodes = strings*.hashCode()
// Result: [49, 50, 51]

More examples can be found on the Groovy documentation.


Follow

Get every new post delivered to your Inbox.