Scala Stack intersect() method with example
In Scala Stack class
, the intersect() method is utilized to return a new stack that consists of elements that are present in both the given stacks.
Method Definition: def intersect[B >: A](that: collection.Seq[B]): Stack[A]
Return Type: It returns a new stack that consists of elements that are present in both the given stacks.
Example #1:
// Scala program of intersect() // method // Import Stack import scala.collection.mutable. _ // Creating object object GfG { // Main method def main(args : Array[String]) { // Creating stacks val s 1 = Stack( 1 , 3 , 2 , 7 , 6 , 5 ) val s 2 = Stack( 1 , 13 , 2 , 17 , 6 , 15 ) // Print the stack println( "Stack_1: " + s 1 ) println( "Stack_2: " + s 2 ) // Applying intersect method val result = s 1 .intersect(s 2 ) // Display output print( "The elements in both the stacks: " ) result.foreach(x => print(x + " " )) } } |
Output:
Stack_1: Stack(1, 3, 2, 7, 6, 5) Stack_2: Stack(1, 13, 2, 17, 6, 15) The elements in both the stacks: 1 2 6
Example #2:
// Scala program of intersect() // method // Import Stack import scala.collection.mutable. _ // Creating object object GfG { // Main method def main(args : Array[String]) { // Creating stacks val s 1 = Stack( 1 , 3 , 2 , 7 , 6 , 5 ) val s 2 = Stack( 11 , 3 , 12 , 7 , 16 , 5 ) // Print the stack println( "Stack_1: " + s 1 ) println( "Stack_2: " + s 2 ) // Applying intersect method val result = s 1 .intersect(s 2 ) // Display output print( "The elements in both the stacks: " + result) } } |
Output:
Stack_1: Stack(1, 3, 2, 7, 6, 5) Stack_2: Stack(11, 3, 12, 7, 16, 5) The elements in both the stacks: Stack(3, 7, 5)
Please Login to comment...