Open In App
Related Articles

Scala Product Map Values

Improve Article
Improve
Save Article
Save
Like Article
Like

In Scala the product of the map elements can be done by utilizing foldLeft method.

Syntax: m1.foldLeft(1)(_*_._1)

Here, m1 is used for a Map, foldLeft is a method that takes an initial value one for product. it will take previous result and multiply it to the next map key value. * and use 1 for the initial value to get the product of values.

Return Type: It returns the product of all the elements of the map.

Example #1:




// Scala program of product()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a map
        val m1 = Map(3 -> "geeks", 2 -> "for", 4 -> "for")
          
        // Applying product method
        val result = m1.foldLeft(1)(_*_._1)
          
        // Displays output
        println(result)
      
    }
}


Output:

24

Here, one in the foldLeft method is the initial value.
Example #2:




// Scala program of product()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a map
        val m1 = Map(3 -> "geeks", 4 -> "for", 4 -> "for")
          
        // Applying product method
        val result = m1.foldLeft(1)(_*_._1)
          
        // Displays output
        println(result)
      
    }
}


Output:

12

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 26 Jul, 2019
Like Article
Save Article
Similar Reads