📜  带有示例的 Scala TreeSet foreach() 方法

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

带有示例的 Scala TreeSet foreach() 方法

在 Scala TreeSet class中, foreach()方法用于将给定函数应用于 TreeSet 的所有元素。

示例 #1:

// Scala program of foreach() 
// method 
  
// Import TreeSet
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating TreeSet
        val t1 = TreeSet(2, 4, 6, 7, 8, 9) 
          
        // Print the TreeSet
        println(t1)
  
        // Applying foreach method to print the TreeSet
        print("Elements in the TreeSet: ") 
        t1.foreach(x => print(x + " "))  
          
    } 
} 
输出:
TreeSet(2, 4, 6, 7, 8, 9)
Elements in the TreeSet: 2 4 6 7 8 9

示例 #2:

// Scala program of foreach() 
// method 
  
// Import TreeSet
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating TreeSet
        val t1 = TreeSet(2, 4, 6, 7, 8, 9) 
          
        // Print the TreeSet
        println(t1) 
          
        // Applying foreach method  
        t1.foreach(x => println(x + " times " + x +" = " + x*x))  
          
    } 
} 
输出:
TreeSet(2, 4, 6, 7, 8, 9)
2 times 2 = 4
4 times 4 = 16
6 times 6 = 36
7 times 7 = 49
8 times 8 = 64
9 times 9 = 81