Scala filter on two conditions

瘦欲@ 提交于 2019-12-03 08:06:32

问题


I would like to filter my data set on two conditions at once.

Is it possible?

I want something like this:

mystuff = mystuff.filter(_.isX && _.name == "xyz")

回答1:


Using slightly less concise lambda syntax:

mystuff = mystuff.filter(x => (x.isX && x.name == "xyz"))

You can find more detail on Scala anonymous function syntax here.




回答2:


While there might be some performance impact depending on what "myStuff" is, you could always filter twice

mystuff = mystuff.filter(_.isX).filter(_.name == "xyz")



回答3:


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.



来源:https://stackoverflow.com/questions/11127594/scala-filter-on-two-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!