groovy学习6-闭包和数据处理

 

代码
   
     

/* *
* @author <a href="mailto:[email protected]">张挺</a>
* @since 2010-4-2 13:06:00
*
*/

// 定义一个闭包,By default closures take 1 parameter called "it"
square = { it * it }
// 像调用函数一样调用
println square( 9 )

// 使用collection.collection方法对list里的每一个数据进行操作
println ([ 1 , 2 , 3 , 4 ].collect({it * 5 + 10 }))

// 使用each遍历map,闭包里有2个参数
printMapClosure = {key, value -> println key + " = " + value }
[
" yue " : " wu " , " lane " : " burks " , " sudha " : " saseethiaseeleethialeselan " ].each(printMapClosure)

// 匿名闭包,省略了()
fullString = ""
orderParts
= [ " BUY " , 200 , " Hot Dogs " , " 1 " ]
orderParts.each {
fullString
+= it + " "
}

println fullString

// 另一个匿名闭包,循环map的keyset
myMap = [ " asdf " : 1 , " qwer " : 2 , " sdfg " : 10 ]

result
= 0
myMap.keySet().each( { result
+= myMap[it] } )
println result

// 使用闭包打印文件内容
myFileDirectory = " C:/ "
myFileName
= " 1.txt "
myFile
= new File(myFileDirectory + myFileName)

printFileLine
= { println " File line: " + it }

myFile.eachLine( printFileLine )

// 字符串处理,字符串可以调toInteger()转成integer
stringDate = " 2005-07-04 "
dateArray
= stringDate.split( " - " ) // split() uses regEx's, so you need to escape chars such as a "." -> "\\."
year = dateArray[ 0 ].toInteger()
year
= year + 1
newDate
= year + " - " + dateArray[ 1 ] + " - " + dateArray[ 2 ]
println newDate

 

 

 

你可能感兴趣的:(groovy)