Scala Queue map()方法及示例

Scala Queue map()方法及示例

map() 方法被用来建立一个新的队列,通过对这个队列的所有元素应用一个函数。

方法定义: def map[B](f: (A) => B):Queue[B]

返回类型。它返回一个新队列,包含应用给定函数后的所有元素。

例子 #1:

// Scala program of map() 
// method 
  
// Import Queue  
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating a queue 
        val q1 = Queue(1, 3, 2, 7, 6, 5) 
          
        // Print the queue
        println(q1)
          
        // Applying map method 
        val result = q1.map(x => x*x)
          
        // Display output
        print("New queue after squaring all elements: " + result)
          
    } 
} 

输出。

Queue(1, 3, 2, 7, 6, 5)
New queue after squaring all elements: Queue(1, 9, 4, 49, 36, 25)

例子#2。

// Scala program of map() 
// method 
  
// Import Queue  
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating a queue 
        val q1 = Queue(1, 3, 2, 7, 6, 5) 
          
        // Print the queue
        println(q1)
          
        // Applying map method 
        val result = q1.map(x => x/2)
          
        // Display output
        print("New queue after dividing all elements by 2: " + result)
          
    } 
} 

输出。

Queue(1, 3, 2, 7, 6, 5)
New queue after dividing all elements by 2: Queue(0, 1, 1, 3, 3, 2)

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程