Skip to content
Related Articles

Related Articles

Scala Stack forall() method with example
  • Last Updated : 03 Nov, 2019

In Scala Stack class, the forall() method is utilized to check if a predicate holds true for all the elements of the stack.

Method Definition: def forall(p: (A) => Boolean): Boolean

Return Type: It returns true if the predicate holds true for all the elements of the stack or else returns false.

Example #1:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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

Example #2:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

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



My Personal Notes arrow_drop_up
Recommended Articles
Page :