Arturo Herrero

10 Groovy one-liners to impress your friends

I believe that comparing programming languages is a worthwhile exercise mainly because of the different techniques and styles that you are exposed to.

After 10 Scala / CoffeeScript / Ruby / Haskell / Clojure / C# / F# / Nim / Swift one-liners to impress your friends, here are the Groovy one-liners.

1. Multiply each item in a list by 2

(1..10)*.multiply(2)

2. Sum a list of numbers

(1..1000).sum()

3. Verify if exists in a string

def wordList = ['groovy', 'akka', 'grails framework', 'spock', 'typesafe']
def tweet = 'This is an example tweet talking about groovy and spock.'
wordList.any { word -> tweet.contains(word) }

4. Read in a file

def fileText = new File('data.txt').text
def fileLines = new File('data.txt').readLines()

5. Happy Birthday to You

(1..4).each { println 'Happy Birthday ' + ((it == 3) ? 'dear Arturo' : 'to You') }

6. Filter list of numbers

def (passed, failed) = [49, 58, 76, 82, 88, 90].split{ it > 60 }

7. Fetch and parse an XML web service

def results = new XmlSlurper().parse('http://arturoherrero.com/index.xml')

8. Find minimum (or maximum) in a list

[14, 35, -7, 46, 98].min()
[14, 35, -7, 46, 98].max()

9. Parallel processing

import groovyx.gpars.*
GParsPool.withPool { def result = dataList.collectParallel { processItem(it) } }

Using Gpars that offers intuitive and safe ways to handle Groovy tasks concurrently.

10. Sieve of Eratosthenes

def t = 2..100
(2..Math.sqrt(t.last())).each { n -> t -= ((2*n)..(t.last())).step(n) }
println t

Bonus: FizzBuzz

for (i in 1..100) { println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i }

June 04, 2011 | @ArturoHerrero