Scala 产品映射值
在 Scala 中,地图元素的乘积可以通过使用foldLeft方法来完成。
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.
示例 #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)
}
}
输出:
24
这里, foldLeft方法中的一个是初始值。
示例 #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)
}
}
输出:
12