.filter()
calls SC-P1009filter
s11 def exists(arr: Array[Int], criteria: Int => Boolean): Boolean = arr.find(criteria).isDefined
12 def filterBy(arr: Array[Int], criteria: Int => Boolean): Array[Int] = arr.filter(criteria)
13 def filterBy(arr: Array[Int], first: Int => Boolean, `then`: Int => Boolean): Array[Int] =
14 arr.filter(first).filter(`then`)15
16 def pickBy(arr: Array[Int], criteria: Int => Boolean): Unit = {
17 for (i <- 0 to arr.length - 1) {
Certain Scala collections support methods such as .filter
, allowing you to select elements from your collection based on specified conditions. Since each filter
call iterates through the entire collection, it is recommended that you combine/chain such consecutive calls to avoid re-iterations.
val filteredElements = elements.filter(x => x % 2 == 0).filter(x => x >= 4)
val filteredElements = elements.filter(x => x % 2 == 0 && x >= 4)