(转)拨动你朋友的11条Groovy超炫代码

(转)打动你朋友的11条Groovy超炫代码
http://www.groovyq.net/content/%E6%89%93%E5%8A%A8%E4%BD%A0%E6%9C%8B%E5%8F%8B%E7%9A%8411%E6%9D%A1groovy%E8%B6%85%E7%82%AB%E4%BB%A3%E7%A0%81



1. List中的每个元素乘2:
(1..10)*.multiply(2)


2. List求和:
//元素均为为数字
(1..1000).sum()
//元素含有字符
['a',3,'z'].sum()  //结果为字符串‘a3z’


3. List中是否含有某个字符串
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) }

//该方法同样适用于对象
class Person{
    String name
}
def person1=new Person(name:'person1')
def person2=new Person(name:'person2')
def person3=new Person(name:'person3')
def wordList = [person1,person2]
def tweet = [person3]
wordList.any { it -> tweet.contains(it) }


上述代码结果为false,如果tweet = [person3,person1],结果就为true

4. 文件内容读取,易如反掌:
//读取所有内容
new File("data.txt").text
//按行读取,返回List
new File("data.txt").readLines()


5. 生日快乐!
(1..4).each { println 'Happy Birthday ' + ((it == 3) ? 'dear Arturo' : 'to You') }


6. 按条件拆分List
def (passed, failed) = [49, 58, 76, 82, 88, 90].split{ it > 60 }


7. 获取和解析XML Web服务
def results = new XmlSlurper().parse('http://search.twitter.com/search.atom?&q=groovy')


8. 找出List中最大最小值:
[14, 35, -7, 46, 98].min()
[14, 35, -7, 46, 98].max()


9. 使用GPars提供的直观、安全的方式控制Groovy的并行任务
import groovyx.gpars.*
GParsPool.withPool { def result = dataList.collectParallel { processItem(it) } }


10.找质数算法(Sieve of Eratosthenes筛法)
def t = 2..100
(2..Math.sqrt(t.last())).each { n -> t -= ((2*n)..(t.last())).step(n) }
println t

这个方法来自于Groovy Prime Numbers的评论。

11.有奖问答:FizzBuzz问题 - 打印1到100这些数字,遇到数字为3的倍数的时候,打印“Fizz”替代数字,5的倍数用“Buzz”代替,既是3的倍数又是5的倍数打印“FizzBuzz”。
for (i in 1..100) {
    println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i
}

另附两个有趣问题的解答:

现在手头有0.5美元、0.25美元、10美分、5美分、1美分,将1美元换成这些零钱,有多少种换法:
def count=0
101.times{ x1 -> 21.times{
    x2 -> 11.times{
        x3 -> 5.times{
            x4 -> 3.times{
                x5 -> if(x1*1+x2*5+x3*10+x4*25+x5*50 == 100){
                         count++
                         println "$x1*1+$x2*5+$x3*10+$x4*25+$x5*50 == 100"
                    }
                }
            }
        }
    }
}
println count


汉诺塔问题:
def hanoita(n, a, b, c){
    if(n==1){
        println "$n : $a -> $c"
    }else{
        hanoita n-1, a, c, b
        println "$n : $a -> $c"
        hanoita n-1, b, a, c
    }
}
hanoita 5, 'a', 'b', 'c'

奇妙吧?就是这么简单!对于上述代码,如果你有更好的提议,也可以分享给大家。