Skip to content

Instantly share code, notes, and snippets.

@aeg
Created February 17, 2013 15:36
Show Gist options
  • Save aeg/4971911 to your computer and use it in GitHub Desktop.
Save aeg/4971911 to your computer and use it in GitHub Desktop.
リストから指定条件を満たす要素を抽出する
// Case #1
// リストの要素を条件で抽出する。
def list1 = ['a', 'b', 'c', 'd']
assert list1.grep{ it > 'b' } == ['c', 'd']
// Case #2
// リストの要素をリストの条件で抽出する。
def list2 = ['a', 'b', 'b', 'c', 'd']
assert list2.grep(['a', 'b']) == ['a', 'b', 'b']
// Case #3
// リストの要素を正規表現の条件で抽出する。
def list3 = ['Appleケーキ', 'Orangeケーキ', 'ショートケーキ', 'モンブラン']
assert list3.grep(~/.*ケーキ$/) == ['Appleケーキ', 'Orangeケーキ', 'ショートケーキ']
// Case #4
// リストの要素を文字列の長さの条件で抽出する。
def list4 = ['apple', 'lemon', 'mellon', 'orange']
assert list4.grep{it.size() > 5} == ['mellon', 'orange']
// Case #5
// リストの要素をある文字列が含まれる条件で抽出する。
assert list4.grep{it.indexOf('on') > 0 } == ['lemon', 'mellon']
// Case #6
// リストの要素をクラスの型で抽出する。
def list6 = [1, 10.5d, true, 'あ']
assert list6.grep(Boolean) == [true]
assert list6.grep(Integer) == [1]
assert list6.grep(String) == ['あ']
assert list6.grep(Double) == [10.5d]
assert list6.grep(Object) == [1, 10.5d, true, 'あ']
assert list6.grep(Iterable) == []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment