• [转]Groovy One Liners to Impress Your Friends


    Link:http://arturoherrero.com/2011/06/04/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 / Python / Haskell / Clojure / C# / F# 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
    

    I found this solution in the comments of this post, Groovy Prime Numbers.

    11. Bonus: FizzBuzz

    for (i in 1..100) { println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i }
    
  • 相关阅读:
    临时产品id记录
    一张图包含SEO一切要点
    Java基础之Volatile原理
    docker
    Linux设置虚拟内存教学和实战
    用最简单的话告诉你什么是ElasticSearch
    git全局配置修改
    数组和字符串方法区别
    git初级使用
    JavaScript的5中基本数据类型
  • 原文地址:https://www.cnblogs.com/buhaiqing/p/4082766.html
Copyright © 2020-2023  润新知