Created
November 5, 2011 07:20
-
-
Save irof/1341227 to your computer and use it in GitHub Desktop.
Groovyのリスト操作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// g100pon #3 リスト操作(上級編) | |
// 1から10まで連番のリストを作成する | |
def list = [*1..10] | |
assert list == [1,2,3,4,5,6,7,8,9,10] | |
// 逆順にする | |
assert list.reverse() == [10,9,8,7,6,5,4,3,2,1] | |
// 後ろから5個とりだす | |
assert list[-5..-1] == [6,7,8,9,10] | |
// 奇数のリストを作る | |
assert list.findAll { it % 2 == 1 } == [1,3,5,7,9] | |
// 全ての値を二乗したリストを作る | |
assert list.collect { it * it } == [1,4,9,16,25,36,49,64,81,100] | |
// 複数要素の追加と削除 | |
list += [11,12,13] | |
assert list == [1,2,3,4,5,6,7,8,9,10,11,12,13] | |
list -= [10,11,13,14] | |
assert list == [1,2,3,4,5,6,7,8,9,12] | |
// 順番をランダムにする | |
Collections.shuffle(list) | |
assert list != [1,2,3,4,5,6,7,8,9,12] | |
// ソートする | |
assert list.sort() == [1,2,3,4,5,6,7,8,9,12] | |
// 入れ子リストを平坦にする | |
list = [1,2,[3,4],5] | |
assert list.flatten() == [1,2,3,4,5] | |
// 一意にする | |
list = [1,1,2,3,4,5,2,2,6] | |
assert list.unique() == [1,2,3,4,5,6] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment