📜  Scala sum Map 值

📅  最后修改于: 2022-05-13 01:55:08.892000             🧑  作者: Mango

Scala sum Map 值

在 Scala 中,地图元素的总和可以通过使用foldLeft方法来完成。

示例 #1:

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

这里, foldLeft方法中的零是初始值。
示例 #2:

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