📜  Scala Map foreach() 方法与示例

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

Scala Map foreach() 方法与示例

foreach() 方法用于将给定函数应用于地图的所有元素。

示例 #1:

// Scala program of foreach()
// method
  
// Creating object
object GfG
{ 
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating map
        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs", 6 -> "geeks")
          
        // Applying foreach method and 
        // displaying output 
        val result = m1.foreach(x => println("key=" + x._1 + ", value=" + x._2))
          
    }
}
输出:
key=3, value=geeks
key=1, value=for
key=2, value=cs
key=6, value=geeks

示例 #2:

// Scala program of foreach()
// method
  
// Creating object
object GfG
{ 
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating map
        val m1 = Map(3 -> "geeks", 1 -> "for", 2 -> "cs", 3 -> "geeks")
          
        // Applying foreach method and 
        // displaying output 
        val result = m1.foreach(x => println("key=" + x._1 + ", value=" + x._2))
          
    }
}
输出:
key=3, value=geeks
key=1, value=for
key=2, value=cs

因此,相同的元素只被采用一次。