Scala Queue forall()方法及示例

Scala Queue forall()方法及示例

forall() 方法是用来检查一个谓词是否对队列中的所有元素都成立。

方法定义: def forall(p: (A) => Boolean):Boolean

返回类型。如果谓词对队列中的所有元素都成立,则返回真,否则返回假。

例子 #1:

// Scala program of forall() 
// method 
  
// Import Queue  
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating queues 
        val q1 = Queue(1, 3, 2, 7, 6, 5) 
          
        // Print the queue
        println(q1)
          
        // Applying forall method 
        val result = q1.forall(x => {x % 7 == 0}) 
          
        // Displays output 
        print("All the elements are divisible by 7: " + result)
    } 
} 

输出。

Queue(1, 3, 2, 7, 6, 5)
All the elements are divisible by 7: false

例子#2。

// Scala program of forall() 
// method 
  
// Import Queue  
import scala.collection.mutable._
  
// Creating object 
object GfG 
{ 
  
    // Main method 
    def main(args:Array[String]) 
    { 
      
        // Creating queues 
        val q1 = Queue(1, 3, 7, 5) 
          
        // Print the queue
        println(q1)
          
        // Applying forall method 
        val result = q1.forall(x => {x % 2 != 0}) 
          
        // Displays output 
        print("All the elements are odd: " + result)
    } 
} 

输出。

Queue(1, 3, 7, 5)
All the elements are odd: true

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程