10 Groovy One Liners to Impress Your Friends
I find 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. Multiple 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://search.twitter.com/search.atom?&q=groovy')
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
11. Bonus: FizzBuzz
for (i in 1..100) { println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i }
June 04, 2011 | @ArturoHerrero