Scala | reduce() Function

The reduce() method is a higher-order function that takes all the elements in a collection (Array, List, etc) and combines them using a binary operation to produce a single value. It is necessary to make sure that operations are commutative and associative. Anonymous functions are passed as parameter to the reduce function.
Syntax:

val l = List(2, 5, 3, 6, 4, 7)
// returns the largest number from the collection
l.reduce((x, y) => x max y)

The order in which numbers are selected for operation by the reduce method is random. This is the reason why non-commutative and non-associative operations are not preferred.
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to
// print maximum value
// using reduce()
  
// Creating object
object GfG
{
      
// Main method
def main(args:Array[String])
{
    // source collection
    val collection = List(1, 3, 2, 5, 4, 7, 6)
  
    // finding the maximum valued element
    val res = collection.reduce((x, y) => x max y)
  
    println(res)
}
}

chevron_right


Output :

7

In the above program, the reduce method selects random pairs and finds out the maximum value in a particular pair. These values are again compared with each other until a single maximum valued element is obtained. We generally make use of the reduce() method along with the map() method while working with Resilient Distributed Datasets in Spark. The map() method helps us to transform a collection to another collection while the reduce() method allows us to perform some action.

Finding average using map() and reduce():
Example :

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program to
// print average
// using map() and reduce()
  
//Creating object
object GfG
{
      
// Main method
def main(args:Array[String])
{
    // source collection
    val collection = List(1, 5, 7, 8)
  
    // converting every element to a pair of the form (x,1)
    // 1 is initial frequency of all elements
    val new_collection = collection.map(x => (x,1))
  
    /*
    List((1, 1), (5, 1), (7, 1), (8, 1))
    */
  
    // adding elements at correspnding positions
    val res = new_collection.reduce( (a,b) => ( a._1 + b._1,
                                            a._2 + b._2 ) )
    /*
    (21, 4)
    */
  
    println(res)
    println("Average="+ res._1/res._2.toFloat)
}
}

chevron_right


Output:

(21, 4)
Average= 5.25

In the above program, all elements of the collection are transformed into tuples with two elements. First element of the tuple is the number itself and the second element is the counter. Initially all counters are set to 1. The output itself is a tuple with two elements: first value is the sum and the second value is the number of elements.
Note: Type of output given by reduce() method is same as the type of elements of the collection.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.