groovy簡明チュートリアル(3)よく使われるクラスと集合

7065 ワード

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は最後から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]