Open In App

Scala Iterator take() method with example

Improve
Improve
Like Article
Like
Save
Share
Report

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:




// 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())
        }
    }
}


Output:

2
3
5
7

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




// 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())
        }
    }
}


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.



Last Updated : 13 Aug, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads