Scala List count() operation with examples

 314 total views,  2 views today

Welcome to Scala series. In this tutorial, you will learn about the Scala List count() operation with examples.

List() is a collection to store values in an ordered fashion. count() operation is a useful operation of the Scala List which allows us to count the number of elements of the list based on a given predicate function. When you call this operation on a Scala list, it returns a count value based on the number of elements in the list. It doesn’t provide the count as such, but we have to pass an anonymous boolean function , and the element which satisfies the boolean function will be considered for count value.

count() Syntax

def count(p: (A) => Boolean): Int

Counts the number of elements in the collection which satisfy a predicate.

Scala List count() operation  example 1

In this example, we are counting elements that have a length lesser than 2.

object FindCount {
  def main(args: Array[String]): Unit = {

    //Create a list
    var list: List[String] = List("a", "b", "c", "d", "a", "c")

    //Find the Count
    println(list.count(ele => ele.length() < 2))
  }
}

Output

6

Scala List count() operation  example 2

In this example, we are counting elements that have a length greater than or equal to 2.

object FindCount {
  def main(args: Array[String]): Unit = {

    //Create a list
    var list: List[Int] = List(1, 2, 3, 4, 5, 6, 7, 8)

    //Find the Count
    println(list.count(ele => ele >= 2))
  }
}

Output

7

ReferencesScala List count operation

Would you like to learn more about Scala features, please check out Scala – a complete guide series. In this tutorial guide, you will find useful Scala functions that can be applied to the collection.

I hope you like this tutorial and you were able to understand Scala list count operation with examples.

Thanks for reading and please give us a thumb up and comment below.

Tags :

About the Author

Rajasekar

Hey There, My name is Rajasekar and I am the author of this site. I hope you are liking my tutorials and references. Programming and learning new technologies are my passion. The ultimate idea of this site is to share my knowledge(I am still a learner :)) and help you out!. Please spread your words about us (staticreference.com) and give a thumbs up :) Feel free to contact me for any queries!.