Sunday, 2 June 2019

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection

To use filter on your collection, give it a predicate to filter the collection elements as desired. Your predicate should accept a parameter of the same type that the collection holds, evaluate that element, and return true to keep the element in the new collection, or false to filter it out. Remember to assign the results of the filtering operation to a new variable.

A predicate is just a method (or function) that returns a boolean value.

For instance, the following example shows how to create a list of even numbers from an input list using a modulus algorithm:
val x = List.range(1, 10)
val evens = x.filter(_ % 2 == 0)

Methods you can use to filter a collection are listed
collect
diff
distinct
drop
dropWhile
filter
filterNot
find
foldLeft
foldRight
head
headOption
init
intersect
last
lastOption
reduceLeft
reduceRight
remove
slice
tail
take
takeWhile
union
Unique characteristics of filter compared to these other methods include:

  • filter walks through all of the elements in the collection; some of the other methods stop before reaching the end of the collection
  • filter lets you supply a predicate to filter the elements
//

val fruits = Set("orange", "peach", "apple", "banana")
fruits: scala.collection.immutable.Set[java.lang.String] = Set(orange, peach, apple, banana)
//
val x = fruits.filter(_.startsWith("a"))
x: scala.collection.immutable.Set[String] = Set(apple)
//
val y = fruits.filter(_.length > 5)
y: scala.collection.immutable.Set[String] = Set(orange, banana)

//
val list = "apple" :: "banana" :: 1 :: 2 :: Nil
val strings = list.filter {
case s: String => true
case _ => false
}
strings: List[Any] = List(apple, banana)

//
def onlyStrings(a: Any) = a match {
    case s: String => true
    case _ => false
}
val strings = list.filter(onlyStrings)

Use filter method to filter a Scala collection

Use filter method to filter a Scala collection To use filter on your collection, give it a predicate to filter the collection elements as...