Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Scala Stack filter() method with example

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

In Scala Stack class, the filter() method is utilized to return a new stack that consists of all the elements that satisfy a given predicate.

Method Definition: def filter(pred: (A) => Boolean): Stack[A]

Return Type: It returns a new stack that consists of all the elements that satisfy a given predicate.

Example #1:




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

Output:

Stack(1, 3, 2, 7, 6, 5)
Odd elements: Stack(1, 3, 7, 5)

Example #2:




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

Output:

Stack(1, 3, 2, 7, 6, 5)
Elements divisible by 3: Stack(3, 6)

My Personal Notes arrow_drop_up
Last Updated : 03 Nov, 2019
Like Article
Save Article
Similar Reads