Scala Tutorial - Learn How To Use Reduce Function With Examples

By Nadim Bahadoor | Last updated: March 16, 2018 at 14:40 pm

Overview

In this tutorial, we will learn how to use the reduce function with examples on collection data structures in Scala. The reduce function is applicable to both Scala's Mutable and Immutable collection data structures.

 

The reduce method takes an associative binary operator function as parameter and will use it to collapse elements from the collection. Unlike the fold method, reduce does not allow you to also specify an initial value.

 

As per the Scala documentation, the definition of the reduce method is as follows:

def reduce[A1 >: A](op: (A1, A1) ⇒ A1): A1

 

The reduce method is a member of the TraversableOnce trait.

Steps

1. How to initialize a sequence of donut prices

The code below show how to initialize a Sequence of type Double to represent donut prices..

println("Step 1: How to initialize a sequence of donut prices")
val donutPrices: Seq[Double] = Seq(1.5, 2.0, 2.5)
println(s"Elements of donutPrices = $donutPrices")

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


Step 1: How to initialize a sequence of donut prices
Elements of donutPrices = List(1.5, 2.0, 2.5)

 

2. How to find the sum of the elements using reduce function

The code below shows how to use the reduce method to find the sum of the Sequence of type Double from Step 1, that is, the sum of donut prices.


println("\nStep 2: How to find the sum of the elements using reduce function")
val sum: Double = donutPrices.reduce(_ + _)
println(s"Sum of elements from donutPrices = $sum")

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


Step 2: How to find the sum of the elements using reduce function
Sum of elements from donutPrices = 6.0

 

3. How to find the sum of elements using reduce function explicitly

In Step 2, we used the reduce method along with the wildcard operator. The example below is similar to the one in Step 2 except that we are using the reduce method explicitly to capture the operator function.


println("\nStep 3: How to find the sum of elements using reduce function explicitly")
val sum1: Double = donutPrices.reduce((a, b) => a + b)
println(s"Sum of elements from donutPrices by calling reduce function explicitly= $sum1")

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


Step 3: How to find the sum of elements using reduce function explicitly
Sum of elements from donutPrices by calling reduce function explicitly= 6.0

 

4. How to find the cheapest donut using reduce function

We can also use the reduce method to find the minimum element in the Sequence of donut prices as shown below.


println("\nStep 4: How to find the cheapest donut using reduce function")
println(s"Cheapest donut price = ${donutPrices.reduce(_ min _)}")

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


Step 4: How to find the cheapest donut using reduce function
Cheapest donut price = 1.5

 

5. How to find the most expensive donut using reduce function

Similar to Step 4, we can use the reduce method to find the maximum element in the Sequence of donut prices.


println("\nStep 5: How to find the most expensive donut using reduce function")
println(s"Most expensive donut price = ${donutPrices.reduce(_ max _)}")

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


Step 5: How to find the most expensive donut using reduce function
Most expensive donut price = 2.5

 

6. How to initialize a Sequence of donuts

The reduce method is of course not limited to Sequence of type Double. Let's create a Sequence of type Double to represent a Sequence of donuts.


println("\nStep 6: 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 6: How to initialize a Sequence of donuts
Elements of donuts = List(Plain Donut, Strawberry Donut, Glazed Donut)

 

7. How to concatenate the elements from the sequence using reduce function

In the mkString method tutorial, we showed how to conveniently create String representation of collection. The code below will instead use the reduce method to concatenate the String elements from the Sequence of donuts.


println("\nStep 7: How to concatenate the elements from the sequence using reduce function")
println(s"Elements of donuts sequence concatenated = ${donuts.reduce((left, right) => left + ", " + right)}")

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


Step 7: How to concatenate the elements from the sequence using reduce function
Elements of donuts sequence concatenated = Plain Donut, Strawberry Donut, Glazed Donut

 

8. How to declare a value function to concatenate donut names

Let's redo the example from Step 7 and show how to declare a value function which will encapsulate combining donut elements of type String.


println("\nStep 8: How to declare a value function to concatenate donut names")
val concatDonutNames: (String, String) => String = (left, right) => {
 left + ", " + right
}
println(s"Value function concatDonutNames = $concatDonutNames")

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


Step 8: How to declare a value function to concatenate donut names
Value function concatDonutNames = <function2>

 

9. How to pass a function to reduce function

With the value function from Step 8, we can now pass it through to the reduce method to concatenate our donut String elements as follows.


println("\nStep 9: How to pass a function to reduce function")
println(s"Elements of donuts sequence concatenated by passing function to the reduce function = ${donuts reduce concatDonutNames}")

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


Step 9: How to pass a function to reduce function
Elements of donuts sequence concatenated by passing function to the reduce function = Plain Donut, Strawberry Donut, Glazed Donut

 

10. How to use option reduce to avoid exception if the collection is empty

You should note that calling the reduce method on an empty collection will throw an exception. To avoid an exception being thrown, you can make use of the convenient reduceOption method instead.


println("\nStep 10: How to use option reduce to avoid exception if the collection is empty")
println(s"Using reduce option will NOT throw any exception = ${Seq.empty[String].reduceOption(_ + ", " + _)}")

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


Step 10: How to use option reduce to avoid exception if the collection is empty 
Using reduce option will NOT throw any exception = None

NOTE:

This concludes our tutorial on Learn How To Use Reduce Function With Examples 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 sequence of donut prices
  • How to find the sum of the elements using reduce function
  • How to find the sum of elements using reduce function explicitly
  • How to find the cheapest donut using reduce function
  • How to find the most expensive donut using reduce function
  • How to initialize a Sequence of donuts
  • How to concatenate the elements from the sequence using reduce function
  • How to declare a value function to concatenate donut names
  • How to pass a function to reduce function
  • How to use option reduce to avoid exception if the collection is empty

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 reduceLeft 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: