All Articles

Filter

Intro

In my post on higher-order-functions I discussed map as a standard.

Suppose you have a collection and you would like to return only those elements for which a given predicate is true. filter is a higher-order function (because it takes a function as an argument) which accomplishes this by taking as its arguments a boolean-valued method and the collection of interest.

  val x: List[Int] = List.range(1, 10)
  val y = x.filter(x => x % 2 == 0)
  println(y)  // List(2, 4, 6, 8)
Published 9 Jul 2018