📜  Scala 不可变 TreeSet foreach() 方法

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

Scala 不可变 TreeSet foreach() 方法

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

示例 #1:

// Scala program of foreach() 
// method 
  
// Import TreeSet
import scala.collection.immutable._
  
// 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.immutable._
  
// 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