filter Method

The Scala filter Method

Notes:

  • filter loops over a sequence
    • It’s like a basic for/yield expression with a guard
  • filter only returns elements that match the filtering expression
    • think "retain"
  • filter takes a function as an argument
    • the function (algorithm) you supply should work on a single element and return a Boolean value (i.e., your function is a predicate)
    • your function’s input parameter type must match the type in the collection
      • ex: if it’s a List[Int], your algorithm should take an Int and return a Boolean

filter examples

Some filter examples:

val xs = (1 to 10).toList

// filter examples
val smalls = xs.filter(x => x < 5)
val smalls = xs.filter(_ < 5)
val larges = xs.filter(_ > 5)
val oops = xs.filter(_ > 100)     // List()

filter is like this much longer for expression:

val ys = 
    for
        x <- xs
        if x > 5
    yield
        x

More examples

val fruits = Seq("orange", "peach", "apple", "banana")

val as = fruits.filter(fruit => fruit.startsWith("a"))   // long
val as = fruits.filter(_.startsWith("a"))                // short

val longNames = fruits.filter(_.length > 5)

Using a function with filter

// a List
val list = "apple" :: "banana" :: 1 :: 2.2 :: Nil

// a function (predicate) that works on any Matchable
def onlyStrings(a: Matchable): Boolean = a match
    case s: String => true
    case _ => false

// use the function with the List and filter
val strings = list.filter(onlyStrings)    // List("apple", "banana")

filter and filterNot

val a = (0 to 100 by 10).toVector
a.filter(_ < 20)       // Vector(0, 10)
a.filter(_ > 1_000)    // Vector()
a.filterNot(_ < 45)    // Vector(50, 60, 70, 80, 90, 100)