Scala Map的一些简单用法(一)

1, 一些例子如下, 看结果就知道功能; 故不做中文解释

scala> val map = Map("1"->"one")
map: scala.collection.immutable.Map[String,String] = Map(1 -> one)
//获取值
scala> map("1")
res2: String = one

scala> map("2")
java.util.NoSuchElementException: key not found: 2
  at scala.collection.MapLike$class.default(MapLike.scala:228)
  at scala.collection.AbstractMap.default(Map.scala:59)
  at scala.collection.MapLike$class.apply(MapLike.scala:141)
  at scala.collection.AbstractMap.apply(Map.scala:59)
  ... 33 elided
//获取值
scala> map.get("1")
res23: Option[String] = Some(one)

scala> map.get("2")
res24: Option[String] = None


//转换成Set
scala> map.toSet
res3: scala.collection.immutable.Set[(String, String)] = Set((1,one))
//转换成Seq(Ele转换成Seq元素)
scala> map.toSeq
res4: Seq[(String, String)] = ArrayBuffer((1,one))
//zhuanhuan scala> map.toString
res5: String = Map(1 -> one)
//key值遍历
scala> map.keys.foreach(x => println(x))
1  scala> map.values.foreach(x=>println(x))
one
//valus值遍历
scala> val map1 = Map("2"->"two")
map1: scala.collection.immutable.Map[String,String] = Map(2 -> two)
//连接两个map
scala> map ++ map1
res10: scala.collection.immutable.Map[String,String] = Map(1 -> one, 2 ->

scala> map
res12: scala.collection.immutable.Map[String,String] = Map(1 -> one)
//判断map是否包含某个元素(key)
scala> if(map.contains("1")) println("yes") else println("false")
yes
//map添加元素,返回一个新的map
scala> map  + ("3"->"three")
res18: scala.collection.immutable.Map[String,String] = Map(1 -> one, 3 -> three)
//"remove"一个元素,返回一个新的map
scala> map - ("1")
res20: scala.collection.immutable.Map[String,String] = Map()
//拼接两个map
scala> val m = map ++ map1
m: scala.collection.immutable.Map[String,String] = Map(1 -> one, 2 -> two)
//更新map的values(存在就更新,不存在就新增)
scala> m.updated("1","6")
res43: scala.collection.immutable.Map[String,String] = Map(1 -> 6, 2 -> two)

scala> m.updated("4","6")
res44: scala.collection.immutable.Map[String,String] = Map(1 -> one, 2 -> two, 4
 -> 6)
//把两个map的元素对应起来返回一个新的map, 若两个map的元素不相等, 以少的个数那个为准
scala> map zip map1
res54: scala.collection.immutable.Map[(String, String),(String, String)] = Map((
1,one) -> (2,two))

scala> map zip m
res55: scala.collection.immutable.Map[(String, String),(String, String)] = Map((
1,one) -> (1,one))

scala> m zip m
res56: scala.collection.immutable.Map[(String, String),(String, String)] = Map((
1,one) -> (1,one), (2,two) -> (2,two))



你可能感兴趣的:(Scala Map的一些简单用法(一))