scala(十八) Map

2021-07-07  本文已影响0人  万事万物

Map 集合

Scala中的Map和Java类似,也是一个散列表,它存储的内容也是键值对(key-value)映射,Scala中不可变的Map是有序的,可变的Map是无序的。

不可变Map

创建不可变Map

val map=Map("a"->1,"b"->2,"c"->3)

或者

val map=Map(("a",1),("b",2),("c",3))

更或者混合使用

val map=Map(("a",1),"b"->2,"c"->3)

只有是二元元组就可以

支持的Api

scala> map.
+              contains       foldLeft             iterator       product             splitAt        toStream
++             copyToArray    foldRight            keySet         reduce              stringPrefix   toString
++:            copyToBuffer   forall               keys           reduceLeft          sum            toTraversable
-              count          foreach              keysIterator   reduceLeftOption    tail           toVector
--             default        genericBuilder       last           reduceOption        tails          transform
/:             drop           get                  lastOption     reduceRight         take           transpose
:\             dropRight      getOrElse            lift           reduceRightOption   takeRight      unzip
WithFilter     dropWhile      groupBy              map            repr                takeWhile      unzip3
addString      empty          grouped              mapValues      runWith             to             updated
aggregate      equals         hasDefiniteSize      max            sameElements        toArray        values
andThen        exists         hashCode             maxBy          scan                toBuffer       valuesIterator
apply          filter         head                 min            scanLeft            toIndexedSeq   view
applyOrElse    filterKeys     headOption           minBy          scanRight           toIterable     withDefault
canEqual       filterNot      init                 mkString       seq                 toIterator     withDefaultValue
collect        find           inits                nonEmpty       size                toList         withFilter
collectFirst   flatMap        isDefinedAt          orElse         slice               toMap          zip
companion      flatten        isEmpty              par            sliding             toSeq          zipAll
compose        fold           isTraversableAgain   partition      span                toSet

+
添加一个元素,返回一个新的map

  @Test
  def map(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val newMap=map.+("d"->4)

    println(newMap)
  }
Map(a -> 1, b -> 2, c -> 3, d -> 4)

++
添加一组map

  @Test
  def map(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val newMap=map.++(List("d"->4,"e"->5,"f"->6))

    println(newMap)
  }
Map(e -> 5, f -> 6, a -> 1, b -> 2, c -> 3, d -> 4)

++:
添加一组map

  @Test
  def map(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val newMap=map.++:(List("d"->4,"e"->5,"f"->6))

    println(newMap)
  }

结果和++一样

Map(e -> 5, f -> 6, a -> 1, b -> 2, c -> 3, d -> 4)

-
根据key删除元素

  @Test
  def map(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val newMap=map.-("a")

    println(newMap)
  }
Map(b -> 2, c -> 3)

--
根据一组key删除元素

  @Test
  def map(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val newMap=map.--(List("a","c"))

    println(newMap)
  }
Map(b -> 2)

map
获取元素,key不存在直接报错

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map("a")

    println(value)
  }
1
  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map("d")

    println(value)
  }
java.util.NoSuchElementException: key not found: d

get
获取元素,返回的是一个Option

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map.get("a")

    println(value)
  }
Some(1)

若要读取数字1,需要再调用一个get

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map.get("a").get

    println(value)
  }
`

若无数据返回Node

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map.get("d")

    println(value)
  }
None

getOrElse 若没数据,可以指定一个默认值

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map.getOrElse("d",4)

    println(value)
  }
4

updated
修改元素

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map.updated("a",100)

    println(value)
  }
Map(a -> 100, b -> 2, c -> 3)

keys
获取map中所有的key

  @Test
  def map1(): Unit ={
    val map=Map(("a",1),"b"->2,"c"->3)

    val value=map.keys

    println(value)
  }
Set(a, b, c)
上一篇下一篇

猜你喜欢

热点阅读