Scala Stack distinct()方法及其示例
在Scala Stack类中, distinct() 方法用于从给定的堆栈中删除重复的元素。
方法定义: def distinct: Stack[A]
返回类型:它返回一个仅带有不同元素的新堆栈。
示例1:
// Scala程序中的distinct()方法
// 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, 1, 2, 1, 3, 2, 3, 3)
// Print the stack
println(s1)
// Applying distinct() method
val result = s1.distinct
// Display output
print("具有不同元素的堆栈:" + result)
}
}
Stack(1, 3, 2, 1, 2, 1, 3, 2, 3, 3)
具有不同元素的堆栈:Stack(1, 3, 2)
示例2:
// Scala程序中的distinct()方法
// Import Stack
import scala.collection.mutable._
// Creating object
object GfG
{
// Main method
def main(args:Array[String])
{
// Creating stack
val s1 = Stack("g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s")
// Print the stack
println(s1)
// Applying distinct() method
val result = s1.distinct
// Display output
print("具有不同元素的堆栈:" + result)
}
}
Stack(g, e, e, k, s, f, o, r, g, e, e, k, s)
具有不同元素的堆栈:Stack(g, e, k, s, f, o, r)
阅读更多:Scala 教程
极客教程