Map 映射
表示一种一一对应关系!
package map
Map 映射:表示一种一一对应关系!
object map01 {
def main(args: Array[String]): Unit = {
// 创建可变的Map 键 值 对
val scores = scala.collection.mutable.Map("alice" -> 90,"bob" -> 85)
// 添加
scores +=("max" ->100)
println(scores)
// 创建不可变 Map
val provinceInfo = scala.collection.immutable.Map("42" -> "湖北")
val newInfo = provinceInfo + ("14" -> "山西")
println(newInfo)
}
}
map 运用
-
添加 +=
-
删除 alice
-
查询,对应的值 ret
-
遍历
package map
object map02 {
def main(args: Array[String]): Unit = {
// 创建可变的Map 键 值 对
val scores = scala.collection.mutable.Map("alice" -> 90,"bob" -> 85)
// 添加
scores +=("max" ->100)
// 2. 删除 alice 删除操作是根据key来做的
scores -="alice"
//3. 查询 eg:查看bob的分数.rst 是一个Option 类型
val rst = scores.get("bob")
if (rst.isEmpty){
println("bob没有成绩")
}else{println(rst.get)}
//4.打印scores
println(scores)
//for
for ((key,value) <- scores){
println(s"${key},${value}分")
}
// foreach
scores.foreach({
case (key,value) => println(s"${key},${value}分")
})
}
}