EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

Scala reduce

By Shalu SharmaShalu Sharma

Home » Software Development » Software Development Tutorials » Scala Tutorial » Scala reduce

Scala reduce

Introduction to Scala reduce Function

Scala reduces function to reduce the collection data structure in Scala. This function can be applied for both mutable and immutable collection data structure. Mutable objects are those whose values are changing frequently whereas immutable objects are those objects that one assigns cannot change itself. Reduce function can be applied to map, sequence, set, and list, etc. This function returns a single value from the collection data structure. In reducing function it merges all the values from the collection data structure and returns on a single value.

Syntax

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

Below is the syntax of Scala reduce:

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

Explanation: This is the syntax to define a reduced function in Scala as per their documentation. In the end, it will return a single value from the group of elements. Let’s see one practice example while de declares it into the program:

val result: Int = collection_name.reduce((a1, b1) => a1 + b1)

Explanation: In the above syntax, we have prepared one collection which is followed by the reduced function it takes two parameters on which we can perform our operation. At last, we will obtain one value as output.

How does reduce Function work in Scala?

Reduce function reduces the number of elements into the collection data structure. What it does internally is it uses binary operation and merges all the available elements into one single element. We can see how it works internally, Suppose we have one list which consists of so many elements like 3, 7, 9, 2, 1, 5. Now we will apply to reduce function on it to generate the single number after adding all the numbers from the list.

1. First, it will take the first element 3. Then it will apply a binary operation on the first and second numbers and merge them to generate the third number.

2. f(3, 7) -> 10, this will generate the third number using the binary operation.

Popular Course in this category
Scala Programming Training (3 Courses,1Project)3 Online Courses | 9+ Hours | Verifiable Certificate of Completion | Lifetime Validity | 1 Project
4.5 (5,548 ratings)
Course Price

View Course

Related Courses
Programming Languages Training (41 Courses, 13+ Projects, 4 Quizzes)All in One Software Development Bundle (600+ Courses, 50+ projects)

3. f(10, 9) -> 19, not the output will be 19 after adding the next two-element.

4. f(19, 2) -> 21 the sum of the next two elements is 21 after applying the binary operation.

5. f(21, 1) -> 22 , next two value sum is 22.

6. f(22, 5) -> 26 now the next two elements are 22 and 5 the merge value would be 26 and this is the last element from the list. So the last value is 26.

It will be generated as the output. In the reduce function we are using Anonymous function to iterate over the object into the list(=>). The operation on reduce function is associative and commutative.

Now we can have a look at one practical example for beginners for more understanding:

Code:

object Main extends App{
// Your code here!
// creating collection
val collection = List(200 , 400, 100, 30, 1000, 500)
// applying reduce function
val res = collection.reduce((x1, y1) => x1 max y1)
}

Explanation: In this example, we are creating one collection data structure list. After that, we are applying to reduce function on the list to try to find out the max element from the list of elements. This will also return as a single value from the list of elements.

Extended class:

  • AbstractIterable[(K, V)]
  • Map[K, V]

Some of the supertype:

  • Map
  • Equals
  • MapFactoryDefaults
  • MapOps
  • PartialFunction
  • AbstractIterable
  • Iterable
  • IterableFactoryDefault
  • IterableOps
  • IterableOnceOps
  • IterableOnceOps

Some known classes:

  • TrieMap
  • AbstractMap
  • HashMap
  • IntMap
  • ListMap
  • Longman
  • Map1
  • Map2
  • Map3
  • Map4
  • withDefault
  • TreeMap
  • TrrSeqMap
  • VectorMap
  • AbstractMap
  • AnyRefMap
  • CollisionProofHashMap
  • LinkedHashMap
  • LongMap
  • WithDefault
  • SystemProperties
  • ListMap
  • OpenHashMap

Methods similar to reduce are followed:

  • reduceLeft
  • reduceRight
  • reduceOption
  • reduceRightOPtion
  • reduceLeftOPtion

Examples to Implement Scala reduce

Below are the examples mentioned :

Example #1

In this example, we are finding out the sum of all elements present in the collection data structure by using a binary operation.

Code:

object Main extends App{
// Your code here!
// creating collection
val list1 = List(200 , 400, 100, 30, 1000, 500)
println("list before ::")
println(list1)
// applying reduce function
val result = list1.reduce((x1, y1) => x1 + y1)
println("list after ::")
println(result)
}

Output:

Scala reduce1

Example #2

In this example, we are finding out the subtraction of all elements present in the collection data structure by using a binary operation.

Code:

object Main extends App{
// Your code here!
// creating collection
val list1 = List(200 , 400, 100, 30, 1000, 500)
println("list before ::")
println(list1)
// applying reduce function
val result = list1.reduce((x1, y1) => x1 - y1)
println("list after ::")
println(result)
}

Output:

Scala reduce2

Example #3

In this example, we are finding out the multiplication of all elements present in to the collection data structure by using a binary operation.

Code:

object Main extends App{
// Your code here!
// creating collection
val list1 = List(200 , 400, 100, 30, 1000, 500)
println("list before ::")
println(list1)
// applying reduce function
val result = list1.reduce((x1, y1) => x1 * y1)
println("list after ::")
println(result)
}

Output:

Scala reduce3

Example #4

In this example, we are finding out the division of all elements present in the collection data structure by using a binary operation.

Code:

object Main extends App{
// Your code here!
// creating collection
val list1 = List(200 , 400, 100, 30, 1000, 500)
println("list before ::")
println(list1)
// applying reduce function
val result = list1.reduce((x1, y1) => x1 / y1)
println("list after ::")
println(result)
}

Output:

division of all elements

Example #5

In this example, we are finding out the minimum of all elements present in the collection data structure by using a binary operation.

Code:

object Main extends App{
// Your code here!
// creating collection
val list1 = List(200 , 400, 100, 30, 1000, 500)
println("list before ::")
println(list1)
// applying reduce function
val result = list1.reduce((x1, y1) => x1 min y1)
println("list after ::")
println(result)
}

Output:

binary operation

Conclusion

Scala reduces function is used to perform the binary operation on the collection elements. We can perform so many types of operations. Also, we can find the maximum and minimum value from the collection using the reduce function. Always remember this reduction will always return a single value as the output of the logic because it will merge all the value from the collection.

Recommended Articles

This is a guide to Scala reduce. Here we discuss an introduction to Scala reduce function, syntax, how does it work with programming examples. You can also go through our other related articles to learn more –

  1. Scala flatMap
  2. Scala Versions
  3. Scala Collections
  4. Scala foreach

Scala Programming Training (3 Courses,1Project)

3 Online Courses

9+ Hours

Verifiable Certificate of Completion

Lifetime Validity

1 Project

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
Scala Tutorial
  • Advanced
    • Constructors in Scala
    • Scala Class Constructor
    • Scala Abstract Class
    • Scala String
    • Scala Collections
    • Scala High Order Functions
    • Scala Date Function
    • Scala Stream
    • Scala Class
    • Scala Function
    • Scala Closure
    • Scala Range
    • Scala Either
    • Scala Random
    • Scala Tuples
    • Scala Partial Function
    • Scala Split
    • Scala Finds
    • Scala List
    • Scala Trait
    • Scala Try Catch
    • Scala Regex
    • Scala Vector
    • Scala Seq
    • Scala Byte
    • Scala ListBuffer
    • Scala ArrayBuffer
    • Scala flatMap
    • Scala HashMap
    • Scala Map Function
    • Scala SortBy
    • Scala Some
    • Scala Generic
    • Scala getOrElse
    • Scala REPL
    • Scala Logging
    • Scala Lambda
    • Scala Queue
    • Scala Set
    • Scala Singleton
    • Scala groupBy
    • Scala reduce
    • Scala filter
    • Scala Option
    • Scala Native
    • Scala DataFrame
    • Scala Anonymous Function
    • Scala Read File
    • Scala Write to File
    • Scala Pattern Matching
    • Scala ClassTag
    • Scala Synchronized
    • Scala zipwithindex
    • Scala Interview Questions
  • Basics
    • What is Scala?
    • Uses of Scala
    • Scala Versions
    • Scala Data Types
    • Scala Companion Object
    • Scala Operators
    • Scala: The Functional Approach
    • Scala Object
    • Scala Implicit
    • Scala IDE
  • Control Flow
    • Scala if else
    • Break in Scala
    • Scala for Loop
    • Scala foreach
    • Scala While Loops

Related Courses

Scala Programming Training Course

Programming Language Course

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - Scala Programming Training (3 Courses,1Project) Learn More