带有示例的 Scala Queue map() 方法
map()方法用于通过将函数应用于此队列的所有元素来构建新队列。
Method Definition: def map[B](f: (A) => B): Queue[B]
Return Type: It returns a new queue containing all the elements after applying the given function.
示例 #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)