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:



filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of map()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an Iterator 
        val iter = Iterator(3, 6, 15, 19, 21)
          
        // Applying map method
        val iter1 = iter.map(x=>{x*3})
          
        // Applying next method
        val result = iter1.next()
          
        // Again applying next method
        val result1 = iter1.next()
          
        // Displays output
        println(result)
        println(result1)
          
    }
}

chevron_right


Output:

9
18

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of map()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an Iterator 
        val iter = Iterator(3, 6, 15, 19, 21)
          
        // Applying map method
        val iter1 = iter.map(y=>{y/3})
          
        // Applying next method
        val result= iter1.next()
          
        // Again applying next method
        val result1= iter1.next()
          
        // Displays output
        println(result)
        println(result1)
          
    }
}

chevron_right


Output:

1
2

Here, first two elements will be divided by three and will get the result into a new iterator.



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.