Scala sum Map values
Last Updated :
26 Jul, 2019
In Scala, the sum of the map elements can be done by utilizing foldLeft method.
Syntax : m1.foldLeft(0)(_+_._1)
Here, m1 is used for a Map, foldLeft is a method that takes an initial value zero. it will take previous result and add it to the next map key value.
Return Type: It returns the sum of all the elements of the map.
Example #1:
object GfG
{
def main(args : Array[String])
{
val m 1 = Map( 3 - > "geeks" , 1 - > "for" , 2 - > "cs" )
val result = m 1 .foldLeft( 0 )( _ + _ . _ 1 )
println(result)
}
}
|
Here, zero in the foldLeft method is the initial value.
Example #2:
object GfG
{
def main(args : Array[String])
{
val m 1 = Map( 3 - > "geeks" , 1 - > "for" , 1 - > "for" )
val result = m 1 .foldLeft( 0 )( _ + _ . _ 1 )
println(result)
}
}
|
Share your thoughts in the comments
Please Login to comment...