从元组ListBuffer中获取随机元素

时间:2016-07-07 11:49:10

标签: scala random

我有这个清单:

val list =  ListBuffer[(String, String)]

是否可以在第二个element的条件下从我的列表库中获取随机element

1 个答案:

答案 0 :(得分: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)