The slice() method belongs to the concrete value members of the class AbstractIterator. It is defined in the class Iterator. It creates a new iterator for the interval given in the slice. The first value present in the slice indicates the start of the element in the new iterator and the second value present in the slice indicates the end.
- Method Definition:
def slice(from: Int, until: Int): Iterator[A]
Where, from implies index of the first element and until implies index of the first element following the slice.
- Return Type:
It returns a new iterator with elements from from until until.
Example :
object GfG
{
def main(args : Array[String])
{
val iter = Iterator( 1 , 2 , 3 , 4 , 5 )
val iter 1 = iter.slice( 1 , 4 )
while (iter 1 .hasNext)
{
println(iter 1 .next())
}
}
}
|
Here, if the interval present in the slice is like (n, m) then the elements will be printed from the nth index till (m-1)th index. The functions hasNext and next are used here to print the elements of the new iterator.
Example :
object GfG
{
def main(args : Array[String])
{
val iter = Iterator( 2 , 4 , 5 , 6 )
val iter 1 = iter.slice( 0 , 3 )
while (iter 1 .hasNext)
{
println(iter 1 .next())
}
}
}
|
Here, the elements are printed from the index zero till the second index.