Scala filter on two conditions

ArraysScalaFilterMultiple Conditions

Arrays Problem Overview


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")

Arrays Solutions


Solution 1 - Arrays

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.

Solution 2 - Arrays

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

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

Solution 3 - Arrays

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionrichsoniView Question on Stackoverflow
Solution 1 - ArraysAlex WilsonView Answer on Stackoverflow
Solution 2 - ArraysDave GriffithView Answer on Stackoverflow
Solution 3 - ArraysparadigmaticView Answer on Stackoverflow