📜  Scala Iterator count() 方法与示例

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

Scala Iterator count() 方法与示例

count()方法属于Abstract Iterator类的具体值成员。它在类IterableOnceOps中定义。它计算所述集合中满足给定谓词的元素的数量。

示例 #1:

// Scala program of count()
// method
  
// Creating object
object GfG
{ 
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an Iterator 
        val iter = Iterator(5, 6, 8)
          
        // Applying count method
        val result = iter.count(x => {x % 3 != 0})
          
        // Displays output
        println(result)
      
    }
}
输出:
2

在这里,只有两个元素满足所述谓词,因此返回两个。
示例 #2:

// Scala program of count()
// method
  
// Creating object
object GfG
{ 
  
    // Main method
    def main(args:Array[String])
    {
      
        // Creating an Iterator 
        val iter = Iterator(4, 6, 10, 11, 13)
          
        // Applying count method
        val result = iter.count(x => {x % 2 == 0})
          
        // Displays output
        println(result)
      
    }
}
输出:
3