当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Scala Mutable SortedMap foreach()用法及代码示例


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

Method Definition: def foreach(f:((A, B)) => Unit):Unit

Return Type: It returns all the elements of the SortedMap after applying the given function to each of them.

范例1:

// Scala program of foreach() 
// method 
import scala.collection.SortedMap 
  
// Creating object 
object GfG 
{  
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating SortedMap 
        val m1 = SortedMap(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=1, value=for
key=2, value=cs
key=3, value=geeks
key=6, value=geeks

范例2:

// Scala program of foreach() 
// method 
import scala.collection.SortedMap 
  
// Creating object 
object GfG 
{  
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating SortedMap 
        val m1 = SortedMap(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=1, value=for
key=2, value=cs
key=3, value=geeks

因此,相同的元素只能使用一次。




相关用法


注:本文由纯净天空筛选整理自Shivam_k大神的英文原创作品 Scala Mutable SortedMap foreach() method with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。