Black monkey house: Scala map Map

This place of learning, on the analogy of the map collection of Java learning can be.

1, constructed immutable Map or

val map1 = Map("Alice" -> 10, "Bob" -> 20, "Kotlin" -> 30)

尖叫提示:List和Map默认使用不可变集合,不可变是长度不能变,值也不能改变,Array的不可变是长度不能改变,元素是可以改变的

2, the configuration of the variable mapping Map

import scala.collection.mutable
val map1 = mutable.Map("Alex" -> 10,"Bob" -> 20,"Kotlin" -> 30)
println(map1)

3, empty HashMap mapping

val map3 = new scala.collection.mutable.HashMap[String, Int]

4, dual tuple

val map4 = Map(("Alice", 10), ("Bob", 20), ("Kotlin", 30))

5, value

If the map is not the value, it will throw an exception, using the contains method to check whether there is a key. If such calls by mapping .get (key) returns an Option objects, either Some, either None.

val maybeInt1 = map1.get("Alice")//建议使用get方法得到map中的元素
val maybeInt2 = map1("Alice")
println(maybeInt1)
println(maybeInt2)

6, the updated value

//更新值
map1("Alex") = 99
println(map1)

//有key就更新,没有key就添加
map1 += ("Alex" -> 24,"Faker" -> 45)
println(map1)

//删除key
map1 -= ("Bob","Kotlin")
println(map1)

//类似于 +=
val map5 = map1 + ("AAA" -> 10, "BBB" -> 20)
println(map5)

7, map and collect the difference

Here knowledge, please understand the experience, will be explained in detail in pattern matching
that inside the map and collect a function name, and Map collection mapping is not the same thing

println("\n map 和 collect 区别----collect忽略匹配不上的----------------")
val map1 = Map("Alice" -> 20,"Bob" -> 30)
map1.map{case(_,age) => println(age+1)}
map1.map(a => a._2+1)
map1.collect{
   case (_,age) => println(age+1)
}

// List(1,2,3,4,"heihei") map{case i:Int => println(i+1)}
List(1,2,3,4,"heihei") collect {case i:Int => println(i+1)}

Reproduced in: https: //www.jianshu.com/p/d66033977a10

Guess you like

Origin blog.csdn.net/weixin_34080571/article/details/91182439