Scala Iterator take() method with example

The take() method belongs to the concrete value member of the class Abstract Iterator. It is utilized to select the first n elements of the stated iterator.

Method Definition: def take(n: Int): Iterator[A]

Where, n is the number of element to take from the given iterator.



Return Type: It returns the first n values from the stated iterator, or the whole iterator, whichever is shorter.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of take()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a Iterator 
        val iter = Iterator(2, 3, 5, 7, 8, 9)
          
        // Applying take method 
        val iter1 = iter.take(4)
          
        // Applying while loop and
        // hasNext() method
        while(iter1.hasNext)
        {
          
            // Applying next() method and
            // displaying output
            println(iter1.next())
        }
    }
}

chevron_right


Output:

2
3
5
7

Here, first four elements are displayed as we have selected first four elements in the method.
Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Scala program of take()
// method
  
// Creating object
object GfG
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating a Iterator 
        val iter = Iterator(2, 3, 5, 7, 8, 9)
          
        // Applying take method 
        val iter1 = iter.take(7)
          
        // Applying while loop and
        // hasNext() method
        while(iter1.hasNext)
        {
          
            // Applying next() method and
            // displaying output
            println(iter1.next())
        }
    }
}

chevron_right


Output:

2
3
5
7
8
9

Here, the whole iterator is displayed as the number of elements in that is shorter than the number of elements selected by the method. so, the shorter one is displayed.



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.