scala集合-Map

2018-10-16  本文已影响0人  invincine

Map也分为可变和不可变集合

Map中的存放的是(key, value)映射,key的值是唯一的

1.定义

不可变Map
scala> val map1 = Map(1 -> 'a', 2 -> 'b', 3 -> 'c')
map1: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b, 3 -> c)

scala> val map2 = Map((1, 'a'), (2, 'b'))
map2: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b)

可变Map
scala> import scala.collection._
import scala.collection._

scala> val map3 = mutable.Map(2 -> 'b', 3 -> 'c')
map3: scala.collection.mutable.Map[Int,Char] = Map(2 -> b, 3 -> c)

2.增删改查

可变集合才可以增删改元素

scala> map3 += 5 -> 'e'
res1: map3.type = Map(2 -> b, 5 -> e, 3 -> c)

scala> map3 += (1 -> 'a', 4 -> 'f')
res2: map3.type = Map(2 -> b, 5 -> e, 4 -> f, 1 -> a, 3 -> c)

#增加元素的key在Map中已存在会直接覆盖
scala> map3 += 4 -> 'd'
res24: map3.type = Map(2 -> b, 5 -> e, 4 -> d, 1 -> a, 3 -> c)

#使用“+”会创建一个新的Map,之前的Map不会变
scala> map3 + (6 -> 'f')
res26: scala.collection.mutable.Map[Int,Char] = Map(2 -> b, 5 -> e, 4 -> d, 1 -> a, 3 -> c, 6 -> f)
scala> map3
res27: scala.collection.mutable.Map[Int,Char] = Map(2 -> b, 5 -> e, 4 -> d, 1 -> a, 3 -> c)

直接删除key即可

scala> map3
res30: scala.collection.mutable.Map[Int,Char] = Map(2 -> b, 5 -> e, 4 -> d, 1 -> a, 3 -> c)

scala> map3 -= 2
res31: map3.type = Map(5 -> e, 4 -> d, 1 -> a, 3 -> c)

scala> map3 -= (5 , 4)
res32: map3.type = Map(1 -> a, 3 -> c)

#使用“-”也会创建一个新的Map,原Map不会变
scala> map3 - (1)
res33: scala.collection.mutable.Map[Int,Char] = Map(3 -> c)

scala> map3
res34: scala.collection.mutable.Map[Int,Char] = Map(1 -> a, 3 -> c)

#使用remove返回的是一个Option,存在值为Some,不存在则为None
scala> map3.remove(1)
res38: Option[Char] = Some(a)

scala> map3
res39: scala.collection.mutable.Map[Int,Char] = Map(3 -> c)

scala> map3
res43: scala.collection.mutable.Map[Int,Char] = Map(3 -> c)

scala> map3(3) = 'a'

scala> map3
res46: scala.collection.mutable.Map[Int,Char] = Map(3 -> a)

#通过key直接访问,如果不存在则会报异常
scala> map2
res48: scala.collection.immutable.Map[Int,Char] = Map(1 -> a, 2 -> b)
scala> map2(1)
res49: Char = a
scala> map2(3)
java.util.NoSuchElementException: key not found: 3

#通过get来访问,返回的是Option类型,存在则为Some,否则为None
scala> map3
res53: scala.collection.mutable.Map[Int,Char] = Map(3 -> a)
scala> map3.get(3)
res54: Option[Char] = Some(a)
scala> map3.get(2)
res55: Option[Char] = None

#通过getOrElse来访问,存在则返回value,不存在返回自定的默认值
scala> map3.getOrElse(2, 'b')
res56: Char = b

3.遍历
遍历方式:map for foreach

scala> map3
res20: scala.collection.mutable.Map[Int,Char] = Map(5 -> e, 4 -> f, 7 -> e, 1 -> a, 6 -> f)

#通过map转换后,重复key值的也会覆盖value
scala> map3.map(t => {
     | (t._2, t._1)
     | }).foreach(println)
(e,7)
(a,1)
(f,6)

scala> map3
res22: scala.collection.mutable.Map[Int,Char] = Map(5 -> e, 4 -> f, 7 -> e, 1 -> a, 6 -> f)

scala> for ((k, v) <- map3) {
     | println(s"${k}----->> ${v}")
     | }
5----->> e
4----->> f
7----->> e
1----->> a
6----->> f
上一篇下一篇

猜你喜欢

热点阅读