Open In App

Scala Stack filter() method with example

Improve
Improve
Like Article
Like
Save
Share
Report

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)


Last Updated : 03 Nov, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads