📜  Scala Iterator take() 方法与示例

📅  最后修改于: 2022-05-13 01:55:22.858000             🧑  作者: Mango

Scala Iterator take() 方法与示例

take()方法属于抽象迭代器类的具体值成员。它用于选择所述迭代器的前n 个元素。

示例 #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

在这里,整个迭代器显示为比方法选择的元素数短的元素数。因此,显示较短的一个。