scala之Map集合

版权声明: https://blog.csdn.net/weixin_39966065/article/details/89792892

目录

 

1.创建Map

2.对集合操作

3.zip:将Array集合相同位置的值进行合并为一个 Tuple

 


1.创建Map


(1)immutable.Map
val ages = Map("Leo" -> 30, "Jen" -> 25, "Jack" -> 23)

(2)mutable.Map

// 创建一个可变的Map
val ages = scala.collection.mutable.Map("Leo" -> 30, "Jen" -> 25, "Jack" -> 23)

// 使用另外一种方式定义Map元素
val ages = Map(("Leo", 30), ("Jen", 25), ("Jack", 23))

// 创建一个空的HashMap
val ages = new scala.collection.mutable.HashMap[String, Int]
val ages = scala.collection.mutable.HashMap[String, Int]() 

2.对集合操作

(1)基础的增,删,改,查
// getOrElse函数
val leoAge = ages.getOrElse("leo", 0)
// 更新Map的元素
ages("Leo") = 31
// 增加多个元素
ages += ("Mike" -> 35, "Tom" -> 40)
// 移除元素
ages -= "Mike"

(2)对map 进行 遍历
// 遍历map的entrySet
for ((key, value) <- ages) println(key + " " + value)
// 遍历map的key
for (key <- ages.keySet) println(key)
// 遍历map的value
for (value <- ages.values) println(value)
// 生成新map,反转key和value
for ((key, value) <- ages) yield (value, key)

(3)map的排序(本身 无序的集合模型)
sortMap 进行 key 的排序:
排序方式:字母,数字排序
val ages = scala.collection.immutable.SortedMap("leo" -> 30, "alice" -> 15, "jen" -> 25)

LinkedHashMap:
排序方式:按照插入的顺序排列
val ages = new scala.collection.mutable.LinkedHashMap[String, Int]
ages("leo") = 30
ages("alice") = 15
ages("jen") = 25

3.zip:将Array集合相同位置的值进行合并为一个 Tuple

val names = Array("leo", "jack", "mike")
val ages = Array(30, 24, 26)
val nameAges = names.zip(ages)
/*
 * Array(("leo",30),("jack",24),("mike",26))
 */
for ((name, age) <- nameAges) println(name + ": " + age)

 

猜你喜欢

转载自blog.csdn.net/weixin_39966065/article/details/89792892
今日推荐