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:
// 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 iter 1 = iter.take( 4 ) // Applying while loop and // hasNext() method while (iter 1 .hasNext) { // Applying next() method and // displaying output println(iter 1 .next()) } } } |
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 iter 1 = iter.take( 7 ) // Applying while loop and // hasNext() method while (iter 1 .hasNext) { // Applying next() method and // displaying output println(iter 1 .next()) } } } |
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.
Recommended Posts:
- Scala Iterator seq() method with example
- Scala Iterator max() method with example
- Scala Map iterator method with example
- Scala Iterator sum() method with example
- Scala Iterator min() method with example
- Scala Iterator map() method with example
- Scala Iterator zip() method with example
- Scala Iterator next() method with example
- Scala Iterator indexWhere() method with example
- Scala Iterator dropWhile() method with example
- Scala Iterator hasDefiniteSize() method with example
- Scala Iterator toList() method with example
- Scala Iterator buffered() method with example
- Scala Iterator duplicate() method with example
- Scala Iterator hasNext() method with example
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.