Skip to content
Related Articles

Related Articles

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

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)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :