带有示例的 Scala 迭代器 drop() 方法
drop()方法属于Abstract Iterator类的具体值成员。它在Iterator和IterableOnceOps类中定义。它用于将迭代器向前移动n位,如果n大于迭代器的长度,则会抛出异常。
Method Definition : def drop(n: Int): Iterator[A]
Where, n is the number of elements to be dropped from the stated iterator.
Return Type : It returns all the elements of the stated iterator except the first n ones.
示例 #1:
// Scala program of drop()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating an Iterator
val iter = Iterator(4, 6, 10, 11, 13)
// Applying drop method
val x = iter.drop(4)
// Applying next method
val result = x.next()
// Displays output
println(result)
}
}
输出:
13
在这里,前四个元素被删除,之后的所有元素都被返回。
示例 #2:
// Scala program of drop()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating an Iterator
val iter = Iterator(2, 3, 4)
// Applying drop method
val x = iter.drop(1)
// Applying next method
val result = x.next()
// Displays output
println(result)
}
}
输出:
3