C/C++教程

Scala集合之Map

本文主要是介绍Scala集合之Map,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

在这里插入图片描述
Map 特质也包含了多个可变和不可变的具体实现类。

  • 生成键值对
scala> val t="a"->1
val t: (String, Int) = (a,1)

scala> val t2=("a",1)
val t2: (String, Int) = (a,1)

scala> val t3=Tuple2("a",1)
val t3: (String, Int) = (a,1)

  • 初始化
val m =Map(t)
  • 根据键值查找值
    apply get getOrElse withDefault withDefaultValue getOrElseUpdate
scala> val m=Map("a"->1,"b"->2,"c"->3)
val m: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> m.get("a")
val res156: Option[Int] = Some(1)

scala> m.get("z")
val res157: Option[Int] = None

scala> m.getOrElse("z",100)
val res159: Int = 100

scala> m("a")
val res160: Int = 1

scala> m("z")
java.util.NoSuchElementException: key not found: z
  at scala.collection.immutable.Map$Map3.apply(Map.scala:399)
  ... 32 elided

scala> val m2=m.withDefault(_.charAt(0)-'a')
val m2: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> val m3=m.withDefaultValue(-1)
val m3: scala.collection.immutable.Map[String,Int] = Map(a -> 1, b -> 2, c -> 3)

scala> m2("z")
val res162: Int = 25

scala> m2("y")
val res163: Int = 24

scala> m3("z")
val res164: Int = -1
  • 包含某个键

contains isDefinedAt

scala> m.contains("a")
val res171: Boolean = true

scala> m.contains("z")
val res172: Boolean = false



scala> m.isDefinedAt("a")
val res175: Boolean = true

scala> m.isDefinedAt("z")
val res176: Boolean = false
  • 增加新的键值对
    ++ + ++: ++= put
  • 删除键
这篇关于Scala集合之Map的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!