foreach()方法用於將給定函數應用於Map的所有元素。
函數定義: def foreach(f: ((A, B)) => Unit): Unit
返回類型: It returns all the elements of the map after applying the given function to each of them.
範例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
因此,相同的元素隻能使用一次。
相關用法
- Scala Set foreach()用法及代碼示例
- Scala TreeSet foreach()用法及代碼示例
- Scala SortedMap foreach()用法及代碼示例
- Scala SortedSet foreach()用法及代碼示例
- Scala Queue foreach()用法及代碼示例
- Scala Stack foreach()用法及代碼示例
- Scala Set +()用法及代碼示例
- Scala Int max()用法及代碼示例
- Scala Int min()用法及代碼示例
注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Scala Map foreach() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。