Open In App

Scala Iterator count() method with example

The count() method belongs to the concrete value members of the class Abstract Iterator. It is defined in the class IterableOnceOps. It counts the number of elements in the stated collection which satisfy the given predicate.

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.



Example #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)
      
    }
}

Output:
2

Here, only two elements satisfies the stated predicate so, two is returned.
Example #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)
      
    }
}

Output:
3

Article Tags :