Scala Iterator count() 方法与示例
count()方法属于Abstract Iterator类的具体值成员。它在类IterableOnceOps中定义。它计算所述集合中满足给定谓词的元素的数量。
Method Definition : def count(p: (A) => Boolean): Int
Where, p is the predicate used.
Return Type :It returns the number of elements satisfying the predicate p.
示例 #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