1. Set
- Unordered, unique and similar to Java
- Variable and immutable
Immutable set:
语法:
1) 创建一个空的不可变集,语法格式:
val/var 变量名 = Set[类型]()
2) 给定元素来创建一个不可变集,语法格式:
val/var 变量名 = Set(元素1, 元素2, 元素3...)
- Basic operations of immutable sets:
- Get the size of the set (size)
- Traverse set (consistent with traverse array)
- Add an element, generate a Set (+)
- Join two sets to generate a Set (++)
- Combine sets and lists to generate a Set (++)
//定义
scala> val a = Set(15000,18000,20000,25000)
a: scala.collection.immutable.Set[Int] = Set(15000, 18000, 20000, 25000)
//获取长度
scala> a.size
res19: Int = 4
//遍历
scala> for(i<-a)println(i)
15000
18000
20000
// 拼接两个集
scala> a ++ Set(6,7,8)
res2: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 8, 4)
// 拼接集和列表
scala> a ++ List(6,7,8,9)
res6: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 9, 2, 7, 3, 8, 4)
Mutable set: The operation is the same as the variable set, that is, you need to import the package import scala.collection.mutable.Set
2. Mapping
- Map can be called a mapping. It is a collection of key-value pairs. In scala, Map is also divided into immutable Map and mutable Map.
Immutable Map:
语法:
val/var map = Map(键->值, 键->值, 键->值...) // 推荐,可读性更好
val/var map = Map((键, 值), (键, 值), (键, 值), (键, 值)...)
看例子:
scala> val map = Map("liuafu"->23,"hurong"->23)
map: scala.collection.immutable.Map[String,Int] = Map(liuafu -> 23, hurong -> 23)
//根据键获取值
scala> map("liuafu")
res24: Int = 23
Variable Map: The definition syntax is consistent with immutable Map. But to define a variable Map, you need to manually import import scala.collection.mutable.Map
About the basic operations of Map:
- Get value (map(key))
- Get all keys (map.keys)
- Get all values (map.values)
- Traverse the map collection
- getOrElse
- Increase key, value pair +
- Delete key-
scala> val map = Map("liuafu"->23,"hurong"->23)
map: scala.collection.immutable.Map[String,Int] = Map(liuafu -> 23, hurong -> 23)
//获取值
scala> map("liuafu")
res24: Int = 23
//获取所有key
scala> map.keys
res25: Iterable[String] = Set(liuafu, hurong)
//获取所有值
scala> map.values
res26: Iterable[Int] = MapLike(23, 23)
//打印所有的学生姓名和年龄
scala> for((x,y) <- a) println(s"$x $y")
lisi 40
zhangsan 30
3. iterator
- Same as in Java
scala> val a = List(18000,20000,22000)
a: List[Int] = List(18000, 20000, 22000)
scala> a.iterator
res29: Iterator[Int] = non-empty iterator
scala> for(i <- a)println(i)
18000
20000
22000