10.17. Using filter to Filter a Collection
Problem
You want to filter the items in a collection to create a new collection that contains only the elements that match your filtering criteria.
Solution
As listed in Recipe 10.3, a variety of methods can be used to filter
the elements of an input collection to produce a new output collection.
This recipe demonstrates the filter
method.
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.
For instance, the following example shows how to create a list of even numbers from an input list using a modulus algorithm:
scala>val x = List.range(1, 10)
x: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9) // create a list of all the even numbers in the list scala>val evens = x.filter(_ % 2 == 0)
evens: List[Int] = List(2, 4, 6, 8)
As shown, filter
returns all
elements from a sequence that return true
when your function/predicate is called.
There’s also a filterNot
method that
returns all elements from a list for which your function returns
false
.
Discussion
The main methods you can use to filter a collection are listed in
Recipe 10.3, and are
repeated here for your convenience: collect
, diff
, distinct
, drop
, dropWhile
, filter
, filterNot
, find
, ...
Get Scala Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.