Scala Stack filter() method with example
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 s 1 = Stack( 1 , 3 , 2 , 7 , 6 , 5 ) // Print the stack println(s 1 ) // Applying filter method val result = s 1 .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 s 1 = Stack( 1 , 3 , 2 , 7 , 6 , 5 ) // Print the stack println(s 1 ) // Applying filter method val result = s 1 .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)
Please Login to comment...