### Scala – Reduce

• date 30th May, 2021 |
• by Prwatech |

Reduce Function is applied on assortment information structure in scala that contains records, sets, guides, succession and tuples. Boundary in the lessen work is a parallel activity which consolidates every one of the components from the assortment and returns a solitary worth. The initial two qualities is joined with the twofold activity and the resultant of that activity consolidates with the following worth of the assortment and atlast we get a solitary worth

use case 1:

``````// Scala program sum of elements
// using reduce function
// Creating object
object prwatech {
// Main method
def main(arg:Array[String])
{
// initialize a sequence of elements
val seq_elements: Seq[Double] = Seq(3.1, 2.0, 1.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(3.1, 2.0, 1.5)
Sum of elements = 6.6
``````

use case 2:

``````// Scala program to find maximum and minimum
// using reduce function
// 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.5)
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.5)
Maximum element = 2.1
Minimum element = 1.5
``````

use case 3:

``````object prwatech {
// Main method
def main(arg:Array[String])
{
// initialize a sequence of elements
val seq_elements: Seq[Double] = Seq(3.5, 2.0)
println(s"Elements = \$seq_elements")

// find the diff of the elements
// using reduce function
val diff: Double = seq_elements.reduce((a, b) => a - b)
println(s"diff of elements = \$diff")
}
}
``````

output:

``````Elements = List(3.5, 2.0)
diff of elements = 1.5
``````

### Quick Support  