當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Scala Iterator take()用法及代碼示例


take()方法屬於類Abstract Iterator的具體值成員。它用於選擇指定迭代器的前n個元素。

函數定義: def take(n: Int): Iterator[A]

Where, n is the number of element to take from the given iterator.



返回類型: 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

在此,整個迭代器顯示為元素數,該元素數少於該方法選擇的元素數。因此,顯示較短的一個。



相關用法


注:本文由純淨天空篩選整理自nidhi1352singh大神的英文原創作品 Scala Iterator take() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。