Monday, August 23, 2010

Having Fun with Groovy

I love browsing over to Groovy Console from time to time to check out scripts that have been recently published. It is a great place to learn Groovy or just have fun with Groovy without having to install anything. In the script below, I wanted to multiply two lists of Strings together so while playing around at the Groovy Console site I wrote:
java.util.ArrayList.metaClass.multiply = { e ->
    def list = new ArrayList()
    delegate.each { a ->
        e.each {
            list.add(a + it)
        }
    }
    list
}

x = ["k1", "k2", "k3"]
y = ["v1", "v2", "v3"]

x * y

Now, there may be a better way of handling this in Groovy, but I get the result I am expecting by implementing the multiply method for the ArrayList MetaClass in the top part of the script.

Then I create my lists, x and y, and multiply (*) them together. Nothing too crazy going on here but this demonstrates the power that Groovy can provide programmers with very little effort. Here is the result:
[k1v1, k1v2, k1v3, k2v1, k2v2, k2v3, k3v1, k3v2, k3v3]


Update:

A few more elegant solutions posted at the Groovy Console site.

Shorter version.*
java.util.ArrayList.metaClass.multiply = { e ->
    delegate.collect { a -> e.collect { a + it } } .flatten()
}

x = ["k1", "k2", "k3"]
y = ["v1", "v2", "v3"]

x * y


Another version.*
java.util.ArrayList.metaClass.multiply = {
    [delegate, it].combinations().collect { a -> a[0] + a[1] }
}

x = ["k1", "k2", "k3"]
y = ["v1", "v2", "v3"]

x * y


No MOP version.**
x = ["k1", "k2", "k3"] 
y = ["v1", "v2", "v3"] 
[x, y].combinations()*.join()


*Courtesy of Paul Holt.
**Courtesy of paulk_asert.