scala语言示例
Scala集 (Scala Set)
A set is a collection of unique items stored. In this tutorial on Scala sets, we will learn about sets in Scala along with the working code.
集合是存储的唯一项的集合。 在有关Scala集的教程中 ,我们将学习Scala中的集以及工作代码。
A set is a collection of unique elements. If a duplicate item is added to the set the item will be discarded.
集合是唯一元素的集合。 如果将重复的项目添加到集合中,则该项目将被丢弃。
Example: {1, 4, 6, 7}
Syntax:
句法:
// 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...)
Sets in Scala can be mutable and immutable too. If a Scala set is mutable (declared from the package: Scala.collection.mutable), the values of its elements can be changed anywhere in the program. For immutable sets (declared from the package: Scala.collection.immutable) this value cannot be changed after initialization. The default declaration of Scala sets will create an immutable object.
Scala中的集合也可以是可变的和不可变的。 如果一个Scala集合是可变的(从包中声明: Scala.collection.mutable ),则可以在程序中的任何位置更改其元素的值。 对于不可变集(从程序包Scala.collection.immutable声明 ),此值在初始化后不能更改。 Scala集的默认声明将创建一个不可变的对象。
The creation of an empty Scala set is also valid. And on the set methods like add, remove, clear, etc are applicable and are in the Scala library.
空Scala集的创建也是有效的。 在设置的方法上,像添加,删除,清除等方法都适用,并且在Scala库中。
Example 1: Declaration of immutable set.
示例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)
}
}
}
Output
输出量
Bikes from Royal Enfield:
HashSet(ThunderBird, Interceptor, Classic 350 , Continental GT, Himalayan)
Score in different subjects:
56
67
90
78
29
Example 2: Creating a mutable set.
示例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)
}
}
}
Output
输出量
Bikes from Royal Enfield:
HashSet(Continental GT, ThunderBird, Himalayan, Classic 350 , Interceptor)
Score in different subjects:
67
56
90
29
78
Example 3: Creating an empty Sets in Scala.
示例3:在Scala中创建一个空Set。
import scala.collection.mutable._
object Main
{
def main(args: Array[String])
{
val empty = Set()
print("An empty Set : ")
println(empty)
}
}
Output
输出量
An empty Set : HashSet()
翻译自: https://www.includehelp.com/scala/set-tutorial-with-examples.aspx
scala语言示例