Scala Iterator take() 方法与示例
take()方法属于抽象迭代器类的具体值成员。它用于选择所述迭代器的前n 个元素。
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.
示例 #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())
}
}
}
输出:
2
3
5
7
在这里,前四个元素显示为我们在方法中选择了前四个元素。
示例 #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())
}
}
}
输出:
2
3
5
7
8
9
在这里,整个迭代器显示为比方法选择的元素数短的元素数。因此,显示较短的一个。