zoukankan      html  css  js  c++  java
  • groovy学习6闭包和数据处理

    代码

    /**
    * @author <a href="mailto:zhangting@taobao.com">张挺</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
  • 相关阅读:
    MongoDB 比较运算符 $eq$gt
    leetcode — median-of-two-sorted-arrays
    leetcode — longest-substring-without-repeating-characters
    leetcode — add-two-numbers
    leetcode — two-sum-iii-data-structure-design
    leetcode — two-sum-ii-input-array-is-sorted
    leetcode — two-sum
    linux 命令 — sed
    linux 命令 — 文件相关
    linux 命令 — lsof
  • 原文地址:https://www.cnblogs.com/xiziyin/p/1703201.html
Copyright © 2011-2022 走看看