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:
object GfG
{
def main(args : Array[String])
{
val iter = Iterator( 2 , 3 , 5 , 7 , 8 , 9 )
val iter 1 = iter.take( 4 )
while (iter 1 .hasNext)
{
println(iter 1 .next())
}
}
}
|
Here, first four elements are displayed as we have selected first four elements in the method.
Example #2:
object GfG
{
def main(args : Array[String])
{
val iter = Iterator( 2 , 3 , 5 , 7 , 8 , 9 )
val iter 1 = iter.take( 7 )
while (iter 1 .hasNext)
{
println(iter 1 .next())
}
}
}
|
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
Share your thoughts in the comments
Please Login to comment...