# 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
```

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.