import org.junit.Test /** *可变和不可变Map的操作、遍历 */ class C3_Map { @Test def immutableMapTest(): Unit = { // 使用另外一种方式定义Map元素 val ageMap = Map(("Leo", 30), ("Jen", 25), ("Jack", 23)) // 创建一个不可变的Map val immutableMap = Map("Leo" -> 30, "Jen" -> 25, "Jack" -> 23) // 获取指定key对应的value,如果key不存在,会报错 val leoAge = ageMap("Leo") // java.util.NoSuchElementException: key not found: leo // val leoAge2 = ages3("leo") // 使用contains函数检查key是否存在 val leoAge3 = if (ageMap.contains("leo")) ageMap("leo") else 0 println(leoAge3) // getOrElse函数 val leoAge4 = ageMap.getOrElse("leo", 0) println(leoAge4) // 更新不可变的map val ages2 = ageMap + ("Mike" -> 36, "Tom" -> 40) // 移除不可变map的元素 val ages3 = ageMap - "Tom" } @Test def mutableMapTest(): Unit = { // ages("Leo") = 31 // 创建一个可变的Map val mutableMap = scala.collection.mutable.Map("Leo" -> 30, "Jen" -> 25, "Jack" -> 23) // 创建一个空的HashMap val ages4 = new scala.collection.mutable.HashMap[String, Int] mutableMap("Leo") = 31 println(mutableMap) // 增加多个元素 mutableMap += ("Mike" -> 35, "Tom" -> 40) // 移除元素 mutableMap -= "Mike" } @Test def forTest(): Unit = { val ageMap = Map(("Leo", 30), ("Jen", 25), ("Jack", 23)) // 遍历map的entrySet for ((key, value) <- ageMap) println(key + " " + value) println // 遍历map的key for (key <- ageMap.keySet) println(key) println // 遍历map的value for (value <- ageMap.values) println(value) println //for 循环中的 yield 会把当前的元素记下来,保存在集合中,循环结束后将返回该集合 // 生成新map,反转key和value val map = for ((key, value) <- ageMap) yield (value, key) println(map) } @Test def otherMapTest(): Unit = { // SortedMap可以自动对Map的key的排序 类似于Java的TreeMap val sortedAges = scala.collection.immutable.SortedMap("c" -> 30, "b" -> 15, "a" -> 25) println(sortedAges) // LinkedHashMap可以记住插入entry的顺序 val linkedHashMap = new scala.collection.mutable.LinkedHashMap[String, Int] linkedHashMap("leo") = 30 linkedHashMap("alice") = 15 linkedHashMap("jen") = 25 println(linkedHashMap) // zip操作 把两个数组合并为 Array[(String, Int)] val names = Array("leo", "jack", "mike") val ages = Array(30, 24, 26) val nameAgeArr = names.zip(ages) for ((name, age) <- nameAgeArr) println(name + ": " + age) } }