Scala Queue foreach()方法及示例

Scala Queue foreach()方法及示例

foreach() 方法是用来对队列中的所有元素应用一个给定的函数。

方法定义: def foreach[U](f: (A) => U):Unit

返回类型。它在对队列中的每个元素应用给定的函数后返回所有的元素。

例子 #1:

// Scala program of foreach() 
// method 
  
// Import Queue  
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating queues 
        val q1 = Queue(1, 3, 2, 7, 6, 5) 
         
        // Applying foreach method to print the queue
        print("Elements in the queue: ")
        q1.foreach(x => print(x + " ")) 
          
    } 
} 

输出。

Elements in the queue: 1 3 2 7 6 5

例子#2。

// Scala program of foreach() 
// method 
  
// Import Queue  
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating queues 
        val q1 = Queue(1, 3, 2, 7, 6, 5) 
          
        // Print the queue
        println(q1)
          
        // Applying foreach method 
        q1.foreach(x => println(x + " times " + x +" = " + x*x)) 
          
    } 
} 

输出。

Queue(1, 3, 2, 7, 6, 5)
1 times 1 = 1
3 times 3 = 9
2 times 2 = 4
7 times 7 = 49
6 times 6 = 36
5 times 5 = 25

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程