Scala Tutorial - Learn How To Use WithFilter Function With Examples
Overview
In this tutorial, we will learn how to use the withFilter function with examples on collection data structures in Scala. The withFilter function is applicable to both Scala's Mutable and Immutable collection data structures.
The withFilter method takes a predicate function and will restrict the elements to match the predicate function. withFilter does not create a new collection while filter() method will create a new collection.
As per the Scala documentation, the definition of the withFilter method is as follows:
def withFilter(p: (A) ⇒ Boolean): FilterMonadic[A, Repr]
The withFilter method is a member of TraversableLike trait.
Steps
1. How to initialize a Sequence of donuts
The code below shows how to create a Sequence of type String to represent a donut collection.
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = List("Plain Donut", "Strawberry Donut", "Glazed Donut")
println(s"Elements of donuts = $donuts")
You should see the following output when you run your Scala application in IntelliJ:
Step 1: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)
2. How to filter elements using the withFilter function
In the Learn How To Use Filter Function tutorial, we showed how to make use of the filter() method to restrict collection elements by the given predicate function which is passed-through the filter() method.
When using the filter() method though a new collection is created with the filtered elements. If you would prefer to avoid the overhead of the new collection, you can make use of the withFilter() method to also restrict collection elements based on a given predicate.
In the example below, we are indeed using the withFilter() method to only look for donut names which start with the character P.
println("\nStep 2: How to filter elements using the withFilter function")
donuts
.withFilter(_.charAt(0) == 'P')
.foreach(donut => println(s"Donut starting with letter P = $donut"))
You should see the following output when you run your Scala application in IntelliJ:
Step 2: How to filter elements using the withFilter function
Donut starting with letter P = Plain Donut
Summary
In this tutorial, we went over the following:
- How to initialize a Sequence of donuts
- How to filter elements using the withFilter function
Tip
Source Code
The source code is available on the allaboutscala GitHub repository.
What's Next
In the next tutorial, I will show you how to use the zip function.