Groovy pdf练习例子

来源:互联网 发布:qt网络编程项目java 编辑:程序博客网 时间:2024/05/29 18:49


具体请下载:http://download.csdn.net/download/wuqilianga/10166448


GroovyTest

class GroovyTest {void test() {def names = ["Ted", "Fred", "Jed", "Ned"]println namesdef shortNames = names.findAll{ it -> it.size() <= 3 }println shortNames.size()shortNames.each{ it -> println it }}static void main(String[] args) {new GroovyTest().test()}}

G1


class G1 {void test() {List list = new ArrayList();list.add(1);list.add(2);def have = falselist.each{println("it的值是:$it")}for(it in list){println it;if(it>5) {have = truebreak;}}def names = ["Ted", "Fred", "Jed", "Ned"]println namesdef shortNames = names.findAll{ it.size() <= 3 }println shortNames.size()shortNames.each{ println it }}static void main(String[] args) {new G1().test()}}

G2

class G2 {void test() {BikeGroovyBean bike = new G2$BikeGroovyBean();bike.setCost(new BigDecimal(100.11111111196))println bike.toString() }static void main(String[] args) {new G2().test()}class BikeGroovyBean {String manufacturer, model, serialNo, statusfinal Integer frameDouble weightBigDecimal costpublic void setCost(BigDecimal newCost) {cost = newCost.setScale(3, BigDecimal.ROUND_HALF_UP)}public String toString() {return """Bike:manufacturer -- $manufacturermodel -- $modelframe -- $frameserialNo -- $serialNo"""}}}

G3

class G3 {void test1(){// normal stringsdef firstname = 'Kate'def surname= "Bush"assert firstname * 2 == 'KateKate'// GStringdef fullname = "$firstname $surname"assert fullname == 'Kate Bush'assert fullname - firstname == ' Bush'assert fullname.padLeft(10) ==' Kate Bush'// indexing (including ranges)assert fullname[0..3] == firstnameassert fullname[-4..-1] == surnameassert fullname[5, 3..1] == 'Beta'}void test() {// normal stringsdef firstname = 'Kate'def surname= "Bush"assert firstname * 2 == 'KateKate'println firstname * 2 == 'KateKate'// GStringdef fullname = "$firstname $surname"assert fullname == 'Kate Bush'assert fullname - firstname == ' Bush'println fullname.padLeft(11)// == ' Kate Bush'// indexing (including ranges)assert fullname[0..3] == firstnameprintln fullname[0..3]assert fullname[-4..-1] == surnameprintln fullname[-4..-1]assert fullname[5, 3..1] == 'Beta'println fullname[5, 3..1,-8,-1]def address = """->$fullname123 First AveNew York""".trim()println addressassert "吴" == "i"println "->lines:"def lines =address.split('\n')println linesassert "吴" == "黄"}static void main(String[] args) {new G3().test()}}

G4
class G4 {void test() {def firstname = 'Kate'def surname= "Bush"g// GStringdef fullname = "$firstname $surname"// Multi-line stringsdef twister = '''\She sells, sea shellsBy the sea shore'''def lines =twister.split('\n')assert lines.size() == 2def address = """$fullname123 First AveNew York""".trim()def lines2 =address.split('\n')assert lines2.size() == 3// Multi-line stringsdef twister2 = '''\She sells, sea shellsBy the sea shore'''def lines3 =twister2.split('\n')assert lines3.size() == 2def address4 = """$fullname123 First AveNew York""".trim()def lines4 =address4.split('\n')assert lines4.size() == 3g}static void main(String[] args) {new G4().test()}}


G5

class G5 {void test() {// more substringsdef string = 'hippopotamus'assert string - 'hippo' - 'mus' + 'to' == 'potato'assert string.replace('ppopotam','bisc') == 'hibiscus'// processing charactersassert 'apple'.toList() == ['a', 'p', 'p', 'l', 'e']//also: 'apple' as String[], 'apple'.split(''), 'apple'.each{}string = "an apple a day"assert string.toList().unique().sort().join() == ' adelnpy'// reversing chars/wordsassert 'string'.reverse() == 'gnirts'string = 'Yoda said, "can you see this?"'def revwords = string.split(' ').toList().reverse().join(' ')assert revwords == 'this?" see you "can said, Yoda'def words = ['bob', 'alpha', 'rotator', 'omega', 'reviver']def bigPalindromes = words.findAll{w -> w == w.reverse() && w.size() > 5}assert bigPalindromes == ['rotator', 'reviver']}static void main(String[] args) {new G5().test()}}

G6

import static java.util.Calendar.getInstance as nowimport java.text.SimpleDateFormatimport groovy.time.TimeCategoryclass G6 {void test() {println now().timedef date = new Date() + 1println dateuse(TimeCategory) {println new Date() + 1.hour + 3.weeks - 2.days}def input = "1998-06-03"def df1 = new SimpleDateFormat("yyyy-MM-dd")date = df1.parse(input)def df2 = new SimpleDateFormat("MMM/dd/yyyy")println 'Date was ' + df2.format(date)}static void main(String[] args) {new G6().test()}}

G7

class G7 {void test() {def x = 3def y = 4assert x + y == 7assert x.plus(y) == 7assert x instanceof Integerassert 0.5 == 1/2 // uses BigDecimal arithmetic as defaultdef a = 2 / 3 // 0.6666666666def b = a.setScale(3, BigDecimal.ROUND_HALF_UP)assert b.toString() == '0.667'assert 4 + 3 == 7 // 4.plus(3)assert 4 - 3 == 1 // 4.minus(3)assert 4 * 3 == 12 // 4.multiply(12)assert 4 % 3 == 1 // 4.mod(3)assert 4 ** 3 == 64 // 4.power(3)assert 4 / 3 == 1.3333333333 // 4.div(3)assert 4.intdiv(3) == 1 // normal integer divisionassert !(4 == 3) // !(4.equals(3))assert 4 != 3 // ! 4.equals(3)assert !(4 < 3) // 4.compareTo(3) < 0assert !(4 <= 3) // 4.compareTo(3) <= 0assert 4 > 3 // 4.compareTo(3) > 0assert 4 >= 3 // 4.compareTo(3) >= 0assert 4 <=> 3 == 1 // 4.compareTo(3)}static void main(String[] args) {new G7().test()}}

G8
class G8 {void test() {/*Lists– Special syntax for list literals– Additional common methods (operator overloading)• Maps– Special syntax for map literals– Additional common methods• Ranges– Special syntax for various kinds of rangesAgile 2007 - 29Submission 631 © ASERT 2007def list = [3, new Date(), 'Jan']assert list + list == list * 2def map = [a: 1, b: 2]assert map['a'] == 1 && map.b == 2def letters = 'a'..'z'def numbers = 0..<10*/def list = [3, new Date(), 'Jan']assert list + list == list * 2def map = [a: 1, b: 2]assert map['a'] == 1 && map.b == 2def letters = 'a'..'z'def numbers = 0..<10assert [1,2,3,4] == (1..4)assert [1,2,3] + [1] == [1,2,3,1]assert [1,2,3] << 1 == [1,2,3,1]assert [1,2,3,1] - [1] == [2,3]assert [1,2,3] * 2 == [1,2,3,1,2,3]assert [1,[2,3]].flatten() == [1,2,3]assert [1,2,3].reverse() == [3,2,1]assert [1,2,3].disjoint([4,5,6])assert [1,2,3].intersect([4,3,1]) == [3,1]assert [1,2,3].collect{ it+3 } == [4,5,6]assert [1,2,3,1].unique().size() == 3assert [1,2,3,1].count(1) == 2assert [1,2,3,4].min() == 1assert [1,2,3,4].max() == 4assert [1,2,3,4].sum() == 10assert [4,2,1,3].sort() == [1,2,3,4]assert [4,2,1,3].findAll{ it%2 == 0 } == [4,2]}static void main(String[] args) {new G8().test()}}

G9
class G9 {void test() {def map = [a:1, 'b':2]println map // ["a":1, "b":2]println map.a // 1println map['a'] // 1println map.keySet() // ["a", "b"]map = [:]// extend the map through assignmentmap[1] = 'a'; map[2] = 'b'map[true] = 'p'; map[false] = 'q'map[null] = 'x'; map['null'] = 'z'assert map == [ 1:'a', 2:'b', (true):'p',(false):'q', (null):'x', 'null':'z' ]def sb = new StringBuffer()[1:'a', 2:'b', 3:'c'].each{ k, v-> sb << "$k:$v, " }assert sb.toString() == '1:a, 2:b, 3:c, 'map = [1:'a', 2:'b', 3:'c']def string = map.collect{ k, v -> "$k:$v" }.join(', ')assert string == '1:a, 2:b, 3:c'assert [[ name: 'Clark', city: 'London' ],[ name: 'Sharma', city: 'London' ],[ name: 'Maradona', city: 'LA' ],[ name: 'Zhang', city: 'HK' ],[ name: 'Ali', city: 'HK' ],[ name: 'Liu', city: 'HK' ]].groupBy { it.city } == [London: [[ name: 'Clark', city: 'London' ], [ name: 'Sharma', city: 'London' ]], LA: [[ name: 'Maradona', city: 'LA' ]], HK: [[ name: 'Zhang', city: 'HK' ],[ name: 'Ali', city: 'HK' ],[ name: 'Liu', city: 'HK' ]]]assert "Hello World!" =~ /Hello/ // Find operatorassert "Hello World!" ==~ /Hello\b.*/ // Match operatordef p = ~/Hello\b.*/ // Pattern operatorassert p.class.name == 'java.util.regex.Pattern'// replace matches with calculated valuesassert "1.23".replaceAll(/./){ ch ->ch.next()} == '2/34'assert "1.23".replaceAll(/\d/){ num ->num.toInteger() + 1} == '2.34'assert "1.23".replaceAll(/\d+/){ num ->num.toInteger() + 1} == '2.24'def str = 'groovy.codehaus.org and www.aboutgroovy.com'def re = '''(?x) # to enable whitespace and comments( # capture the hostname in $1(?: # these parens for grouping only(?! [-_] ) # neither underscore nor dash lookahead[\\w-] + # hostname component\\. # and the domain dot) + # now repeat whole thing a few times[A-Za-z] # next must be a letter[\\w-] + # now trailing domain part) # end of $1 capture'''def finder = str =~ redef out = str(0..<finder.count).each{def adr = finder[it][0]out = out.replaceAll(adr,"$adr [${InetAddress.getByName(adr).hostAddress}]")}println out// => groovy.codehaus.org [63.246.7.187]// and www.aboutgroovy.com [63.246.7.76]}static void main(String[] args) {new G9().test()}}

 更多。。。。请下载书籍学习。








原创粉丝点击