Scala Tutorial - Learn How To Use Size Function With Examples
Overview
In this tutorial, we will learn how to use the size function with examples on collection data structures in Scala. The size function is applicable to both Scala's Mutable and Immutable collection data structures.
The size method calculates the number of elements in a collection and return its size.
As per the Scala documentation, the definition of the size method is as follows:
def size: Int
The size method is a member of TraversableOnce trait.
Steps
1. How to initialize a Sequence of donuts
The code below shows how to create a Sequence of donut elements of type String.
println("Step 1: How to initialize a Sequence of donuts")
val donuts: Seq[String] = Seq("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 count the number of elements in the sequence using size function
The code below shows how to call the size method to count the number of elements in the donut Sequence from Step 1.
println("\nStep 2: How to count the number of elements in the sequence using size function")
println(s"Size of donuts sequence = ${donuts.size}")
You should see the following output when you run your Scala application in IntelliJ:
Step 2: How to count the number of elements in the sequence using size function
Size of donuts sequence = 3
3. How to use the count function
The size method should not be confused with the count method. As an example, the code below shows how to use the count method to count the number of times the element Plain Donut appear in the donut Sequence.
println("\nStep 3: How to use the count function")
println(s"Number of times element Plain Donut appear in donuts sequence = ${donuts.count(_ == "Plain Donut")}")
You should see the following output when you run your Scala application in IntelliJ:
Step 3: How to use the count function
Number of times element Plain Donut appear in donuts sequence = 1
Summary
In this tutorial, we went over the following:
- How to initialize a Sequence of donuts
- How to count the number of elements in the sequence using size function
- How to use the count 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 slice function.