`
jamie.wang
  • 浏览: 344929 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

groovy简明教程(三)常用的类及集合

    博客分类:
  • Java
阅读更多

5.1 GString

groovy.lang.GString是对java String的扩展:常量表示更加方便,提供了更多的方法。

 

'hello world'
"hello $name"
'''-------
python style string
 -------'''
"""
triple double quote
with $Gstring aware
"""
/back slash safe \t, \widows\path/
char c='a'; // declare character explicitly
date = "Current London time is ${new Date().toGMTString()}"
province = 'Sichuan'
city = 'Chengdu'
addr = "I am in city: $city province: $province, you?"
println "${addr.strings[0]}, ${addr.strings[1]}, ${addr.values[0]}, ${addr.values[1]}"
// output: I am in city: ,  province: , Chengdu, Sichuan
println addr[2..3] // output: am
sb = 'i am a string'
sb <<= ' changed to a stringbuffer'
sb << ' now can append' // sb is: i am a string changed to a stringbuffer now can append

 5.2 数字对象

groovy为数字对象提供了更多的方法

 

r = ''
10.times {
    r += '*' // output: **********
}
s = 0
1.upto(10) { i -> // 10 is inclusive
    s += i
} // s= 55
2.downto(-2) { i ->
    print "$i," // output: 2,1,0,-1,-2,
}
0.step(10, 2) { i ->
    print "$i," // output: 0,2,4,6,8,
}

5.3 range

(0..3).contains(2) // result: true
(1..<5).size() // result: 4, 5 is excluded

for (e in 5..9) { // loop by range
    print "$e," // output: 5,6,7,8,9,
}

(5..1).each { i -> // reverse range
    print "$i," // output: 5,4,3,2,1,
}

(5..<1).each { i ->
    print "$i," // output: 5,4,3,2, 
}
(1..5).isCase(3) // true

age = 23
switch(age) {
    case 0..8 : println 'kid'; break
    case 9..17 : println 'yang'; break
    case 18..50 : println 'grown up'; break
    default : println 'old'; break
} // result: grown up
all = [1,2,3,4,5,6,7,8,9]
greater = 5..10
lesser = all.grep(greater) // result: 
[5, 6, 7, 8, 9]

 groovy的类只要:

a. 实现了next和previous,也即重载了:++和--操作符,;

b. 实现了java.lang.Comparable接口,也即重载了<=>操作符;

就可以使用range

class RomaNumber implements Comparable {
    private static final Numbers = ['z', 'I','II','III','IV','V'];
    private int digit;
    RomaNumber(int digit) {
        this.digit = digit;
    }
    RomaNumber next() {
        return new RomaNumber((digit + 1) % Numbers.size());
    }
    RomaNumber previous() {
        return new RomaNumber(digit - 1);
    }
    int compareTo(Object o) {
        return this.digit <=> o.digit; // call CompareTo()
    }
    String toString() {
        return Numbers[digit];
    }
}

def one = new RomaNumber(1);
def four = new RomaNumber(4);

for (num in one..four) {
    print "$num,"; // output: I,II,III,IV,
}

5.4 list

groovy借鉴了很多脚本语言,对list做了很多扩展,使之更方便使用。

list的index可为负数,-1是最后一个元素的索引,-2是倒数第二个,以此类推。并且访问超出范围的索引不会抛异常,而是返回null。

list还重载了操作符。提供了很多支持闭包的方法。

 

/***** index *****/
lst = ['a','b','c','d',1,2,3,4] // elements with different type
println lst[0..2] // get elements in range, output: [a, b, c]
println lst[3,5] // get elements of indexes, output: [d, 2]
lst[2..3]=['x','y','z'] // put elements in range, replace and add, result: [a, b, x, y, z, 1, 2, 3, 4]
lst[-1..<-3]=[] // clear elements in range, result: [a, b, x, y, z, 1, 2]
lst[0,1]=[-1,-3] // put elements in indexes, result: [-1, -3, x, y, z, 1, 2]
println lst[10] // get elements out of bounds, no exception, result: null

/***** operator overload *****/
lst += 'I' // plus(object), result: [-1, -3, x, y, z, 1, 2, I]
lst += ['II','IV'] // // plus(collection), result: [-1, -3, x, y, z, 1, 2, I, II, IV]
lst -= [-1,-3,'x','y','z',1,2] // minus(collection), result: [I, II, IV]
lst * 2 // multiply(integert), result: [I, II, IV, I, II, IV]

/***** convient op *****/
println lst.grep(['V', 'II', 'VI']) // intersection, output: [II, II]
switch('I') {
    case lst : println 'true'; break // contains? output: true
    default : println 'false'; break
}
lst.pop() // op like stack, result: [I, II, IV, I, II]
lst=[]
if (!lst) { // empty list is false
    println 'lst is empty' // output: lst is empty
}
lst = [[1,3],[-1,2]]
lst.sort { a,b -> a[0] <=> b[0] } // compare by first element: output: [[-1, 2], [1, 3]]

lst= [1,2,5]
lst.remove 2 // remove by index, not value, result: [1, 2]
// method accept closure as paramters
println lst.collect { item -> item * 2 } // transfer collection to another: output:[2, 4]
println lst.findAll { item -> item % 2 == 0 } // find by closure, output: [2]

5.5 map

groovy 也为map提供了更多方便的操作,和更多的方法。
def amap = [a:1, b:2, c:3] // hash map with key is string, quote(') can be omit
def emptyMap = [:]
str = 'k'
amap[(str)] = 10 // use variable as key
amap.find({entry -> entry.value < 2}) // first entry matching the closure condition, result: entry[a=1]
amap.findAll {entry -> entry.key > 'b'} //  finds all entries(map) matching the closure condition, reusult: [c:3, k:10]
amap['f.b'] = 'foobar'
println amap.'f.b' // output: foobar

/*** retrieve elements ***/
println amap['a']
println amap.a
println amap.get('a')
println amap.get('d',0) // get with default value, output: 0

/*** GDK added methods ***/
amap.any { entry -> entry.value > 2 } // checks whether the predicate is valid for at least one entry, result: true
amap.every { entry -> entry.key < 'c' } // check whether the predict is valid for every entry, result: false
amap.each { k, v -> 
    print k; print v // output: a1b2c3k10f.bfoobard0
}
amap.subMap(['a','b']) // submap with key ['a','b']

/*** tree map ***/
def tmap = new TreeMap() // TreeMap
tmap.put('z', 1)
tmap.put('k', 2) // result: [k:2, z:1]
 

 

 

分享到:
评论

相关推荐

    Groovy入门教程[参照].pdf

    Groovy 入门教程 Groovy 是一种基于 Java 语言的脚本语言,运行在 JVM 中,语法与 Java 相似,但抛弃了 Java 的一些烦琐的语法规则,提供了更加简洁和灵活的编程体验。 Groovy 的特点 1. 简洁的语法:Groovy 语法...

    Groovy入门教程.doc

    创建Groovy类非常直观,例如创建一个名为`HelloWorld`的类,包含一个main方法。在Groovy中,不需要像Java那样显式声明`public`、`static`和`void`,可以直接编写`main(def args)`。Groovy允许省略变量的类型声明,...

    Java中使用Groovy的三种方式

    本文将深入探讨在Java项目中使用Groovy的三种主要方式,并阐述它们各自的优势和应用场景。 一、作为嵌入式脚本 Java 6引入了JSR 223(Scripting for the Java Platform),允许在Java程序中直接执行脚本语言。...

    精通 Groovy 中文教程

    ### 精通Groovy中文教程 #### 一、Groovy简介 Groovy是一种动态语言,专门为Java平台设计,提供了一种更为简洁且灵活的语法结构。Groovy并不旨在取代Java,而是作为Java的一种补充,使得开发者能够在Java环境中...

    groovy基础教程源码,很全面

    Groovy基础教程源码涵盖了Groovy语言的各个方面,是学习和理解Groovy语言的宝贵资源。下面将详细阐述Groovy的一些核心知识点。 1. **动态类型与静态类型**: Groovy支持动态类型,这意味着变量在声明时无需指定...

    Groovy中文教程

    1. 更简洁的类定义:Groovy允许省略分号、花括号,甚至类声明中的public关键字。 2. 支持闭包:Groovy的闭包类似于函数引用,可以作为参数传递,是函数式编程的重要组成部分。 3. 动态类型:Groovy允许不指定变量...

    groovy和Java相互调用1

    标题中的“Groovy和Java相互调用1”指的是在编程时如何在Groovy语言环境中调用Java类,以及反之,如何在Java程序中调用Groovy类。这是一种跨语言交互的方式,特别是在混合使用Groovy和Java的项目中非常常见。 ...

    Groovy语法系列教程之字符串(三).pdf

    ### Groovy语法系列教程之字符串(三) #### Groovy语言简介 Groovy是基于Java平台的一种敏捷开发语言,它具有动态语言的特性,同时又能与Java无缝集成。Groovy的设计哲学是让程序员能够用更少的代码做更多的事情,...

    groovy 1.7官方教程

    ### Groovy 1.7 官方教程知识点详解 #### 一、Groovy简介 - **定义**:Groovy是一种灵活且动态的语言,专为Java虚拟机(JVM)设计。 - **特点**: - **继承优势**:在保留Java强项的基础上,引入了更多来自Python...

    Groovy中文版教程

    4. **元编程**:Groovy允许在运行时修改或扩展类的行为,这是通过元编程实现的。这对于创建自定义的编程模式或者DSL特别有用。 5. **与Java的无缝集成**:Groovy可以调用Java代码,反之亦然。这意味着你可以在同一...

    Java调用Groovy,实时动态加载数据库groovy脚本

    2. 创建GroovyClassLoader:使用这个类加载器可以动态加载和执行Groovy脚本。它继承自Java的ClassLoader,能解析Groovy源码并生成字节码。 3. 加载并执行Groovy脚本:通过GroovyClassLoader的`parseClass()`方法...

    Groovy Script 入门

    #### 三、Groovy脚本的基本使用 ##### 3.1 安装与配置 1. **安装Java环境**:Groovy依赖于Java运行环境,确保已经安装了Java SE Development Kit (JDK)。 2. **下载Groovy**:访问Groovy官方网站...

    Groovy中文教程.pdf

    ### Groovy中文教程知识点概述 #### 一、Groovy简介与快速入门 ##### 1.1 使用Groovy - **Groovy** 是一种基于 **Java虚拟机 (JVM)** 的编程语言,它提供了简洁的语法,并且兼容Java的类库。Groovy能够直接运行在...

    apache-groovy-sdk-2.4.11

    了解 Groovy 对 Java 语法的简化变形,学习 Groovy 的核心功能,例如本地集合、内置正则表达式和闭包。编写第一个 Groovy 类,然后学习如何使用 JUnit 轻松地进行测试。借助功能完善的 Groovy 开发环境和使用技能,...

    Groovy教程.7z

    Groovy 是一种基于Java平台的面向对象语言。Groovy 的语法和 Java 非常的相似,可以使用现有的 Java 库来进行 Groovy 开发。可以将它想像成 Java 语言的一种更加简单、表达能力更强的变体。

    groovy常用Script

    4. **目录操作**:`directory_01.groovy` 可能包含了处理文件系统目录的代码,Groovy提供了一系列的类和方法来操作文件和目录,如`java.io.File`和`java.nio.file`包。 5. **字符串操作**:`string_01.groovy` 可能...

    Groovy入门教程(一).pdf

    对于集成开发环境(IDE),Eclipse是常见的选择,通过安装Groovy插件(支持Groovy 1.5.7及以上版本)可以支持Groovy项目的开发。安装插件的过程可以通过Eclipse的Software Updates功能,添加远程站点并选择Groovy ...

Global site tag (gtag.js) - Google Analytics