Scala学习笔记-06-数据结构-Map

  • 一系列键值对的容器
  • 键是唯一的,但值不必是唯一的
  • 可以根据键进行快速检索
  • 类别:scala.collection.mutable.Map 和 scala.collection.immutable.Map,默认是使用不可变Map

scala.collection.immutable.Map:

//定义Map
scala> val mapDogs = Map("huahua"->"雪纳瑞","erdan"->"秋田犬","happy"->"泰迪") mapDogs: scala.collection.immutable.Map[String,String] = Map(huahua -> 雪纳瑞, erdan -> 秋田犬, happy -> 泰迪) scala> mapDogs res91: scala.collection.immutable.Map[String,String] = Map(huahua -> 雪纳瑞, erdan -> 秋田犬, happy -> 泰迪)
// 按照key获取map的值 scala> mapDogs("huahua") res92: String = 雪纳瑞
// 根据key取值前先判断key是否存在Map中,否则给默认值 scala> val dogType = if(mapDogs.contains("huahua")) mapDogs("huahua") else "no dog name in map keys" dogType: String = 雪纳瑞 scala> val dogType = if(mapDogs.contains("huahua123")) mapDogs("huahua") else "no dog name in map keys" dogType: String = no dog name in map keys

// immutable Map 的值不能修改
scala> mapDogs("huahua") = "雪纳瑞串串"
:46: error: value update is not a member of scala.collection.immutable.Map[String,String]
       mapDogs("huahua") = "雪纳瑞串串"
       ^

 

scala.collection.mutable.Map:

scala> import scala.collection.mutable.Map
import scala.collection.mutable.Map

scala> val mapDogs = Map("huahua"->"雪纳瑞","erdan"->"秋田犬","happy"->"泰迪")
mapDogs: scala.collection.mutable.Map[String,String] = Map(huahua -> 雪纳瑞, erdan -> 秋田犬, happy -> 泰迪)
// 修改元素的值
scala> mapDogs("huahua") = "雪纳瑞串串"

scala> mapDogs
res96: scala.collection.mutable.Map[String,String] = Map(huahua -> 雪纳瑞串串, erdan -> 秋田犬, happy -> 泰迪)

// 添加新元素
scala> mapDogs("tony") = "哈士奇"

mapDogs += ("keven"->"金毛")

 

 

 

---

你可能感兴趣的:(Scala学习笔记-06-数据结构-Map)