我想一次在两个条件下过滤我的数据集。
可能吗?
我想要这样的东西:
mystuff = mystuff.filter(_.isX && _.name == "xyz")
我想一次在两个条件下过滤我的数据集。
可能吗?
我想要这样的东西:
mystuff = mystuff.filter(_.isX && _.name == "xyz")
使用稍微不那么简洁的 lambda 语法:
mystuff = mystuff.filter(x => (x.isX && x.name == "xyz"))
您可以在此处找到有关 Scala 匿名函数语法的更多详细信息。
虽然根据“myStuff”的不同可能会对性能产生一些影响,但您始终可以过滤两次
mystuff = mystuff.filter(_.isX).filter(_.name == "xyz")
If you need to frequently filter with several predicate, you could define a way of combining them:
case class And[A]( p1: A=>Boolean, p2: A=>Boolean ) extends (A=>Boolean) {
def apply( a: A ) = p1(a) && p2(a)
}
Here is how to use it to keep only the odd numbers bigger than 10:
scala> (0 until 20) filter And( _ > 10, _ % 2 == 1 )
res3: scala.collection.immutable.IndexedSeq[Int] = Vector(11, 13, 15, 17, 19)
It easy to write Or
and Not
combinators in the same fashion.