當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Scala Stack count()用法及代碼示例


在 Scala Stack class,則count()方法用於計算堆棧中滿足給定謂詞的元素數。

函數定義: def count(p: (A) => Boolean): Int

返回類型: It returns the count the number of elements in the stack that satisfies a given predicate.



範例1:

// Scala program of count()  
// method  
  
// Import Stack  
import scala.collection.mutable._
  
// Creating object  
object GfG  
{  
  
    // Main method  
    def main(args:Array[String])  
    {  
      
        // Creating a stack  
        val s1 = Stack(1, 2, 3, 4, 5)  
          
        // Print the stack  
        println(s1)  
          
        // Applying count method  
        val result = s1.count(z => true)  
          
        // Displays output  
        print("Number of element in stack: " + result)  
    }  
} 
輸出:
Stack(1, 2, 3, 4, 5)
Number of element in stack: 5

範例2:

// Scala program of count()  
// method  
  
// Import Stack  
import scala.collection.mutable._
  
// Creating object  
object GfG  
{  
  
    // Main method  
    def main(args:Array[String])  
    {  
      
        // Creating a stack  
        val s1 = Stack(1, 2, 3, 4, 5)  
          
        // Print the stack  
        println(s1)  
          
        // Applying count method  
        val result = s1.count(z => {z % 2 == 0})  
          
        // Displays output  
        print("Number of element in stack divisible by 2: " + result)  
    }  
} 
輸出:
Stack(1, 2, 3, 4, 5)
Number of element in stack divisible by 2: 2


相關用法


注:本文由純淨天空篩選整理自rupesh_rao大神的英文原創作品 Scala Stack count() method with example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。