Scala – Reduce

  • date 25th May, 2021 |
  • by Prwatech |
  • 0 Comments

Reduce function is applied on collection arrangement in scala that contains lists, sets, maps, sequence and tuples. Parameter within the reduce function may be a boolean operation which merges all elements from the gathering and returns one value. the primary two values is combined with the boolean operation and therefore the resultant of that operation combines with subsequent value of the gathering and atlast we obtain one value.

use case 1:

object prwatech {
// Main method
    def main(arg:Array[String])
    {
        // initialize a sequence of elements
        val seq_elements: Seq[Double] = Seq(1.5, 2.0, 0.5)
        println(s"Elements = $seq_elements") 
  
        // find the sum of the elements
        // using reduce function
        val sum: Double = seq_elements.reduce((a, b) => a + b)
        println(s"Sum of elements = $sum")
    }   
}

output:

Elements = List(1.5, 2.0, 0.5)
Sum of elements = 4.0

use case 2:

// Creating object
object prwatech {
 // Main method
    def main(arg:Array[String])
    {
        // initialize a sequence of elements
        val seq_elements : Seq[Double] = Seq(2.1, 2.0, 1.1)
        println(s"Elements = $seq_elements")
  
        // find the maximum element using reduce function
        val maximum : Double = seq_elements.reduce(_ max _)
        println(s"Maximum element = $maximum")
  
        // find the minimum element using reduce function
        val minimum : Double = seq_elements.reduce(_ min _)
        println(s"Minimum element = $minimum")
    }
}

output

Elements = List(2.1, 2.0, 1.1)
Maximum element = 2.1
Minimum element = 1.1

use case 3:

object prwatech {
// Main method
    def main(arg:Array[String])
    {
        // initialize a sequence of elements
        val seq_elements: Seq[Double] = Seq(1.5, 2.0, 0.5)
        println(s"Elements = $seq_elements") 
  
        // find the Multiplication of the elements
        // using reduce function
        val Mult: Double = seq_elements.reduce((a, b) => a * b)
        println(s"Multiplication of elements = $Mult")
    }   
}

output:

Elements = List(1.5, 2.0, 0.5)
Multiplication of elements = 1.5

Quick Support

image image