Scala Tutorial - Learn How To Use Collect Function
Overview
In this tutorial, we will learn how to use the collect function on collection data structures in Scala. The collect function is applicable to both Scala's Mutable and Immutable collection data structures.
The collect method takes a Partial Function as its parameter and applies it to all the elements in the collection to create a new collection which satisfies the Partial Function.
As per the Scala documentation, the definition of the collect method is as follows:
def collect[B](pf: PartialFunction[A, B]): Traversable[B]
The collect method is a member of the TraversableLike trait.
Steps
1. How to initialize a Sequence which contains donut names and prices
The code below shows how to initialize a Sequence which will contain String elements for donut names and Double elements for the donut prices.
println("Step 1: How to initialize a Sequence which contains donut names and prices")
val donutNamesandPrices: Seq[Any] = Seq("Plain Donut", 1.5, "Strawberry Donut", 2.0, "Glazed Donut", 2.5)
println(s"Elements of donutNamesAndPrices = $donutNamesandPrices")
You should see the following output when you run your Scala application in IntelliJ:
Step 1: How to initialize a Sequence which contains donut names and prices
Elements of donutNamesAndPrices = List(Plain Donut, 1.5, Strawberry Donut, 2.0, Glazed Donut, 2.5)
2. How to use collect function to cherry pick all the donut names
The code below shows how to use the collect function to cherry pick only the donut names which are of String types.
println("\nStep 2: How to use collect function to cherry pick all the donut names")
val donutNames: Seq[String] = donutNamesandPrices.collect{ case name: String => name }
println(s"Elements of donutNames = $donutNames")
NOTE:
- We are making use of a Partial Function to filter elements of type String.
3. How to use collect function to cherry pick all the donut prices
The code below shows how to use the collect function to cherry pick only donut prices which are of Double types.
println("\nStep 3: How to use collect function to cherry pick all the donut prices")
val donutPrices: Seq[Double] = donutNamesandPrices.collect{ case price: Double => price }
println(s"Elements of donutPrices = $donutPrices")
You should see the following output when you run your Scala application in IntelliJ:
Step 3: How to use collect function to cherry pick all donut prices
Elements of donutPrices = List(1.5, 2.0, 2.5)
Summary
In this tutorial, we went over the following:
- How to initialize a Sequence which contains donut names and prices
- How to use collect function to cherry pick all the donut names
- How to use collect function to cherry pick all the donut prices
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 diff function.