Home »
Scala
BitSet count() Method in Scala
By IncludeHelp Last updated : November 09, 2024
BitSet in Scala is a special collection of positive integers. Scala programming language has a huge library containing a lot of utility functions to help working with data structure easy.
BitSet count() method
BitSet count() method is used to count the total number of elements present in the BitSet.
Syntax
bitSet_Name.count(x:true)
Parameters
It accepts a single parameter.
Return Type
It returns an integer value which is the count of elements in the array.
Let's see some examples to understand the working of the method.
Example 1
Program to illustrate the working of count() method
// Program to illustrate the working of count() method
import scala.collection.immutable.BitSet
object MyObject {
def main(args: Array[String]): Unit = {
val myBitSet = BitSet(4, 1, 6, 2, 9)
println("myBitSet : " + myBitSet)
val eleCount = myBitSet.count(x => true)
println("The count of elements in BitSet is " + eleCount)
}
}
Output
myBitSet : BitSet(1, 2, 4, 6, 9)
The count of elements in BitSet is 5
Explanation
In the above code, we have created a BitSet named myBitSet with some elements and printed it. Then we have used the count method to count the number of elements in BitSet and printed it.
Example 2
Program to illustrate the working of count() method
// Program to illustrate the working of count() method
import scala.collection.immutable.BitSet
object MyObject {
def main(args: Array[String]): Unit = {
val myBitSet = BitSet()
println("myBitSet : " + myBitSet)
val eleCount = myBitSet.count(x => true)
println("The count of elements in BitSet is " + eleCount)
}
}
Output
myBitSet : BitSet()
The count of elements in BitSet is 0
Explanation
In the above code, we have created a BitSet named myBitSet with 0 elements. Then we have used the count() method to find the number of elements in the BitSet and printed the value.
Example 3
Program to illustrate the working of the count() method
// Program to illustrate the working of count() method
import scala.collection.immutable.BitSet
object MyObject {
def main(args: Array[String]): Unit = {
val myBitSet = BitSet(4, 1, 6, 2, 9)
println("myBitSet : " + myBitSet)
val eleCount = myBitSet.count(x => false)
println("The count of elements in BitSet is " + eleCount)
}
}
Output
myBitSet : BitSet(1, 2, 4, 6, 9)
The count of elements in BitSet is 0