Scala集合教程及示例
ScalaSet
集合是存储的唯一项的集合。在有关Scala集的教程中,我们将学习Scala中的集以及工作代码。
集合是唯一元素的集合。如果将重复的项目添加到集合中,则该项目将被丢弃。
Example: {1, 4, 6, 7}语法:
// for creating immutable set,
val set_name : Set[type] = Set(items...)
val set_name = Set[type] = Set(items...)
// for creating mutable set,
var set_name : Set[type] = Set(items...)
var set_name = Set(items...)Scala中的集合也可以是可变的和不可变的。如果一个Scala集合是可变的(从包中声明:Scala.collection.mutable),则可以在程序中的任何位置更改其元素的值。对于不可变集合(从程序包Scala.collection.immutable声明),该值在初始化后不能更改。Scala集的默认声明将创建一个不可变的对象。
空Scala集的创建也是有效的。在设置的方法上,如添加,删除,清除等方法都适用,并且在Scala库中。
示例1:不可变集的声明。
import scala.collection.immutable._
object Main
{
def main(args: Array[String])
{
val Bikes: Set[String] = Set("ThunderBird", "Classic 350 ", "Continental GT", "Interceptor", "Himalayan")
val Score = Set(78, 67, 90, 56, 29)
println("Bikes from Royal Enfield: ")
println(Bikes)
println("Score in different subjects: ")
for(myset<-Score)
{
println(myset)
}
}
}输出结果
Bikes from Royal Enfield: HashSet(ThunderBird, Interceptor, Classic 350 , Continental GT, Himalayan) Score in different subjects: 56 67 90 78 29
示例2:创建可变集。
import scala.collection.mutable._
object Main
{
def main(args: Array[String])
{
var Bikes: Set[String] = Set("ThunderBird", "Classic 350 ", "Continental GT", "Interceptor", "Himalayan")
var Score = Set(78, 67, 90, 56, 29)
println("Bikes from Royal Enfield: ")
println(Bikes)
println("Score in different subjects: ")
for(myset<-Score)
{
println(myset)
}
}
}输出结果
Bikes from Royal Enfield: HashSet(Continental GT, ThunderBird, Himalayan, Classic 350 , Interceptor) Score in different subjects: 67 56 90 29 78
示例3:在Scala中创建一个空Set。
import scala.collection.mutable._
object Main
{
def main(args: Array[String])
{
val empty = Set()
print("An empty Set : ")
println(empty)
}
}输出结果
An empty Set : HashSet()