Scala Tutorial - Learn How To Use Aggregate Function

By Nadim Bahadoor | Last updated: February 6, 2020 at 12:05 pm

Overview

In this tutorial, we will learn how to use the aggregate function on collection data structures in Scala. The aggregate function is applicable to both Scala's Mutable and Immutable collection data structures. As a reminder, the aggregate function has been deprecated on Scala’s sequential data structures starting with the Scala 2.13.0 version. Therefore, if you are using Scala 2.13.0 version, the aggregate function is designed to work with the Parallel Collections. Moreover, as of Scala 2.13.0, you need to explicitly add the Parallel Collections as a dependency in your build.sbt file. You can find more detailed instructions to setup the Parallel Collections from our tutorial on using the par function for Scala 2.13.0 and above.

 

The aggregate method aggregates results by first applying a sequence operation which is its first parameter and then uses a combine operator to combine the results produced by the sequence operation.

 

As per the Scala documentation for version prior to 2.13.0, the definition of the aggregate method is as follows. The aggregate method was a member of the TraversableOnce trait.


def aggregate[B](z: =>B)(seqop: (B, A) => B, combop: (B, B) => B): B = foldLeft(z)(seqop)

 

As per the Scala documentation for version starting with 2.13.0, the definition of the aggregate method is as follows. With Scala version 2.13.0, and as per the Parallel Collections GitHub repository, the aggregate function is a member of the ParIterableLike trait and is defined as follows:


def aggregate[S](z:=>S)(seqop: (S,T) => S, combop: (S,S) => S): S ={
  tasksupport.executeAndWaitResult(new Aggregate(() => z, seqop, combop, splitter))  
}

 

Steps

1. How to initialize a Set of type String to represent Donut elements 

The code below shows how to initialize a Set of type String which we will use to represent a basket of Donut elements.


println("Step 1: How to initialize a Set of type String to represent Donut elements")
val donutBasket1: Set[String] = Set("Plain Donut", "Strawberry Donut")
println(s"Elements of donutBasket1 = $donutBasket1")

 

You should see the following output when you run your Scala application in IntelliJ:


Step 1: How to initialize a Set of type String to represent Donut elements
Elements of donutBasket1 = Set(Plain Donut, Strawberry Donut)

 

2. How to define an accumulator function to calculate the total length of the String elements

The code below shows how to define an accumulator function which we will use to calculate the total length for all the Donut elements.


println("\nStep 2: How to define an accumulator function to calculate the total length of the String elements")
val donutLengthAccumulator: (Int, String) => Int = (accumulator, donutName) => accumulator + donutName.length

NOTE:

3. How to call aggregate function with the accumulator function from Step 2

The code below shows how to pass the accumulator value function from Step 2 to the aggregate method in order to calculate the total length of the Donut elements.



println("\nStep 3: How to call aggregate function with the accumulator function from Step 2")
val totalLength = donutBasket1.aggregate(0)(donutLengthAccumulator, _ + _)
println(s"Total length of elements in donutBasket1 = $totalLength")

You should see the following output when you run your Scala application in IntelliJ:


Step 3: How to call aggregate function with the accumulator function from Step 2
Total length of elements in donutBasket1 = 27

 

4. How to initialize a Set of Tuple3 elements to represent Donut name, price and quantity

The code below shows how to create a Set of Donut elements where each Donut elements is a Tuple3 to represent the donut's name, price and quantity.


println("\nStep 4: How to initialize a Set of Tuple3 elements to represent Donut name, price and quantity")
val donutBasket2: Set[(String, Double, Int)] = Set(("Plain Donut", 1.50, 10), ("Strawberry Donut", 2.0, 10))
println(s"Elements of donutBasket2 = $donutBasket2")

You should see the following output when you run your Scala application in IntelliJ:


Step 4: How to initialize a Set of Tuple3 elements to represent Donut name, price and quantity
Elements of donutBasket2 = Set((Plain Donut,1.5,10), (Strawberry Donut,2.0,10))

NOTE:

5. How to define an accumulator function to calculate the total cost of Donuts

The code below shows how to define an accumulator Value Function which we will use to calculate the total cost for all donuts.


println("\nStep 5: How to define an accumulator function to calculate the total cost of Donuts")
val totalCostAccumulator: (Double, Double, Int) => Double = (accumulator, price, quantity) => accumulator + (price * quantity)

 

6. How to call aggregate function with accumulator function from Step 5

The code below shows how to pass-through the accumulator function from Step 5 to the aggregate method in order to calculator the total cost for all the donut elements in the Set.


println("\nStep 6: How to call aggregate function with accumulator function from Step 5")
val totalCost = donutBasket2.aggregate(0.0)((accumulator: Double, tuple: (String, Double, Int)) => totalCostAccumulator(accumulator, tuple._2, tuple._3), _ + _)
println(s"Total cost of donuts in donutBasket2 = $totalCost")

You should see the following output when you run your Scala application in IntelliJ:


Step 6: How to call aggregate function with accumulator function from Step 5
Total cost of donuts in donutBasket2 = 35.0

 

This concludes our tutorial on Learn How To Use Aggregate Function and I hope you've found it useful!

 

Stay in touch via Facebook and Twitter for upcoming tutorials!

 

Don't forget to like and share this page :)

Summary

In this tutorial, we went over the following:

  • How to initialize a Set of type String to represent Donut elements
  • How to define an accumulator function to calculate the total length of the String elements
  • How to call aggregate function with the accumulator function from Step 2
  • How to initialize a Set of Tuple3 elements to represent Donut name, price and quantity
  • How to define an accumulator function to calculate the total cost of Donuts
  • How to call aggregate function with accumulator function from Step 5

Tip

  • Review the tutorials on Mutable and Immutable collection data structures in Scala.

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 collect function.

Nadim Bahadoor on FacebookNadim Bahadoor on GithubNadim Bahadoor on LinkedinNadim Bahadoor on Twitter
Nadim Bahadoor
Technology and Finance Consultant with over 14 years of hands-on experience building large scale systems in the Financial (Electronic Trading Platforms), Risk, Insurance and Life Science sectors. I am self-driven and passionate about Finance, Distributed Systems, Functional Programming, Big Data, Semantic Data (Graph) and Machine Learning.
Other allaboutscala.com tutorials you may like: