Scala Iterator map() method with example
The map() method belongs to the concrete value member of the class Abstract Iterator. It is utilized to build a new iterator by applying a function to each of the elements of the stated iterator.
Method Definition:
def map[B](f: (A) => B): Iterator[B]
where, B is the element type of the returned iterator and f is the function to be applied on each element of the iterator.
Return Type:
It returns a new iterator from the stated iterator after applying the function to each element of the given iterator.
Example #1:
object GfG
{
def main(args : Array[String])
{
val iter = Iterator( 3 , 6 , 15 , 19 , 21 )
val iter 1 = iter.map(x => {x* 3 })
val result = iter 1 .next()
val result 1 = iter 1 .next()
println(result)
println(result 1 )
}
}
|
Here, the function is applied to all the elements of the stated iterator and we can see here for the first two elements, where three is multiplied to each of them, similarly it is multiplied to all the elements of the stated iterator resulting into a new iterator.
Example #2:
object GfG
{
def main(args : Array[String])
{
val iter = Iterator( 3 , 6 , 15 , 19 , 21 )
val iter 1 = iter.map(y => {y/ 3 })
val result = iter 1 .next()
val result 1 = iter 1 .next()
println(result)
println(result 1 )
}
}
|
Here, first two elements will be divided by three and will get the result into a new iterator.
Last Updated :
13 Aug, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...