当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Scala Stack intersect()用法及代码示例


在 Scala Stack class,则使用intersect()方法返回一个新堆栈,该堆栈由两个给定堆栈中都存在的元素组成。

函数定义: def intersect[B >: A](that: collection.Seq[B]): Stack[A]

返回类型: It returns a new stack that consists of elements that are present in both the given stacks.



范例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 s1 = Stack(1, 3, 2, 7, 6, 5)  
          
        val s2 = Stack(1, 13, 2, 17, 6, 15) 
          
        // Print the stack  
        println("Stack_1: " + s1)  
            
        println("Stack_2: " + s2) 
            
        // Applying intersect method   
        val result = s1.intersect(s2)  
          
        // Display output  
        print("The elements in both the stacks: ")  
            
        result.foreach(x => print(x + " ")) 
          
    }  
} 
输出:
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

范例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 s1 = Stack(1, 3, 2, 7, 6, 5)  
          
        val s2 = Stack(11, 3, 12, 7, 16, 5) 
          
        // Print the stack  
        println("Stack_1: " + s1)  
            
        println("Stack_2: " + s2) 
            
        // Applying intersect method   
        val result = s1.intersect(s2)  
          
        // Display output  
        print("The elements in both the stacks: " + result)  
         
    }  
} 
输出:
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)


相关用法


注:本文由纯净天空筛选整理自rupesh_rao大神的英文原创作品 Scala Stack intersect() method with example。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。