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:
import scala.collection.mutable. _
object GfG
{
def main(args : Array[String])
{
val s 1 = Stack( 1 , 3 , 2 , 7 , 6 , 5 )
println(s 1 )
val result = s 1 .filter(x => {x % 2 == 1 })
println( "Odd elements: " + result)
}
}
|
Output:
Stack(1, 3, 2, 7, 6, 5)
Odd elements: Stack(1, 3, 7, 5)
Example #2:
import scala.collection.mutable. _
object GfG
{
def main(args : Array[String])
{
val s 1 = Stack( 1 , 3 , 2 , 7 , 6 , 5 )
println(s 1 )
val result = s 1 .filter(x => {x % 3 == 0 })
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
Share your thoughts in the comments
Please Login to comment...