打动你朋友的11条Groovy超炫代码

Dustin Marx在其博文中,跟读者分享了11条Groovy的超炫代码。

  1. List中的每个元素乘2:
1 (1..10)*.multiply(2)
List求和:
1//元素均为为数字
2 (1..1000).sum()
3//元素含有字符
4 ['a',3,'z'].sum()  //结果为字符串‘a3z’
List中是否含有某个字符串
1 def wordList = ['groovy''akka''grails framework''spock','typesafe']
2 def tweet = 'This is an example tweet talking about groovy and spock.'
3 wordList.any { word -> tweet.contains(word) }
01//该方法同样适用于对象
02 class Person{
03     String name
04}
05 def person1=new Person(name:'person1')
06 def person2=new Person(name:'person2')
07 def person3=new Person(name:'person3')
08 def wordList = [person1,person2]
09 def tweet = [person3]
10 wordList.any { it -> tweet.contains(it) }

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

文件内容读取,易如反掌:
1//读取所有内容
2 new File("data.txt").text
3//按行读取,返回List
4 new File("data.txt").readLines()
生日快乐!
1 (1..4).each println 'Happy Birthday ' + ((it == 3) ? 'dear Arturo' 'to You') }
按条件拆分List
1 def (passed, failed) = [495876828890].split{ it > 60 }
获取和解析XML Web服务
1 def results = newXmlSlurper().parse('http://search.twitter.com/search.atom?&q=groovy')
找出List中最大最小值:
1 [1435, -74698].min()
2 [1435, -74698].max()
使用 GPars提供的直观、安全的方式控制Groovy的并行任务
1 import groovyx.gpars.*
2 GParsPool.withPool { def result = dataList.collectParallel { processItem(it) } }
找质数算法(Sieve of Eratosthenes筛法)
1 def t = 2..100
2 (2..Math.sqrt(t.last())).each { n -> t -= ((2*n)..(t.last())).step(n) }
3 println t

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

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

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

现在手头有0.5美元、0.25美元、10美分、5美分、1美分,将1美元换成这些零钱,有多少种换法:

01 def count=0
02 101.times{ x1 -> 21.times{
03     x2 -> 11.times{
04         x3 -> 5.times{
05             x4 -> 3.times{
06                 x5 -> if(x1*1+x2*5+x3*10+x4*25+x5*50 == 100){
07                          count++
08                          println "$x1*1+$x2*5+$x3*10+$x4*25+$x5*50 == 100"
09                     }
10                 }
11             }
12         }
13     }
14}
15 println count

汉诺塔问题:

01 def hanoita(n, a, b, c){
02     if(n==1){
03         println "$n : $a -> $c"
04     }else{
05         hanoita n-1, a, c, b
06         println "$n : $a -> $c"
07         hanoita n-1, b, a, c
08     }
09}
10 hanoita 5'a''b''c'

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值