Skip to content

Instantly share code, notes, and snippets.

@aeg
Last active December 13, 2015 22:08
Show Gist options
  • Select an option

  • Save aeg/4981905 to your computer and use it in GitHub Desktop.

Select an option

Save aeg/4981905 to your computer and use it in GitHub Desktop.
リストからランダムに1つだけ要素を選ぶ
// Case #1
// リストからランダムに1つだけ要素を選ぶ
def list1 = ['a', 'b', 'c', 'd']
def item = list1[new Random().nextInt(list1.size())]
println item
// 実行結果例(実行する度に結果が異なる)
// c
// Case #2
// リスト(ArrayList) にランダムで1つだけ要素を返すメソッドを追加する。
ArrayList.metaClass.define {
random {
int size = delegate.size()
delegate[new Random().nextInt(size)]
}
}
println list1.random()
// 実行結果例(実行する度に結果が異なる)
// a
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment