Scala Queue map() method with example
Last Updated :
29 Oct, 2019
The map() method is utilized to build a new queue by applying a function to all elements of this queue.
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.
Example #1:
import scala.collection.mutable. _
object GfG
{
def main(args : Array[String])
{
val q 1 = Queue( 1 , 3 , 2 , 7 , 6 , 5 )
println(q 1 )
val result = q 1 .map(x => x*x)
print( "New queue after squaring all elements: " + result)
}
}
|
Output:
Queue(1, 3, 2, 7, 6, 5)
New queue after squaring all elements: Queue(1, 9, 4, 49, 36, 25)
Example #2:
import scala.collection.mutable. _
object GfG
{
def main(args : Array[String])
{
val q 1 = Queue( 1 , 3 , 2 , 7 , 6 , 5 )
println(q 1 )
val result = q 1 .map(x => x/ 2 )
print( "New queue after dividing all elements by 2: " + result)
}
}
|
Output:
Queue(1, 3, 2, 7, 6, 5)
New queue after dividing all elements by 2: Queue(0, 1, 1, 3, 3, 2)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...