Scala Map count() 方法与示例
count()方法用于计算 Map 中的键对。
Method Definition: def count(p: ((A, B)) => Boolean): Int
Return Type: It returns the number of keys present in the map that satisfies the given predicate.
示例 #1:
// Scala program of count()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val m1 = Map("geeks" -> 5, "for" -> 3, "cs" -> 5)
// Applying count method
val result = m1.count(z=>true)
// Displays output
println(result)
}
}
输出:
3
示例 #2:
// Scala program of count()
// method
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating a map
val m1 = Map("geeks" -> 5, "for" -> 3, "geeks" -> 5)
// Applying count method
val result = m1.count(z=>true)
// Displays output
println(result)
}
}
输出:
2
因此,相同的键只计算一次。