2016-07-07 4 views
0

からランダム要素を取得し、私はこのリストを持っている:タプルListBuffer

val list = ListBuffer[(String, String)] 

は、それが第二elementから条件に、私のリストベースからランダムelementを取得することはできますか?

+1

あなたは*とはどういう意味ですか」に基づきます第2の要素「*」におけるオン状態である。 'ListBuffer'の第2要素ですか?あなたが話すこの状態は何ですか? –

答えて

0

あなたが意味する場合 - この述語によってfilterすることができますし、その結果からランダムな要素を選択してください - 特定の述語を渡すものからランダムにタプルを取得:

scala> import scala.collection.mutable.ListBuffer 
scala> import scala.util.Random 

// some data 
scala> val list = ListBuffer[(String, String)](("ab", "c"), ("de", "f"), ("gh", "c")) 
list: scala.collection.mutable.ListBuffer[(String, String)] = ListBuffer((ab,c), (de,f), (gh,c)) 

// some predicate on String: 
scala> val f: String => Boolean = s => s == "c" 
f: String => Boolean = <function1> 

// this is not the most efficient way, for small lists it would do: 
scala> Random.shuffle(list.filter(t => f(t._2))).head 
res7: (String, String) = (ab,c) 

// OR, if you're concerned about performance you can: 
scala> val filtered = list.filter(t => f(t._2)) 
filtered: scala.collection.mutable.ListBuffer[(String, String)] = ListBuffer((ab,c), (gh,c)) 

scala> filtered(Random.nextInt(filtered.length)) 
res8: (String, String) = (ab,c) 
関連する問題