Scala Collection-Map

1.Map 有兩種類型,可變與不可變,區別在於可變對象可以修改它,而不可變對象不可以。

可變map:需要顯式的引入 import scala.collection.mutable.Map 類

 

Map 基本操作

方法 描述
keys 返回 Map 所有的鍵(key)
values 返回 Map 所有的值(value)
isEmpty 在 Map 爲空時返回true

 

Map 合併

你可以使用 ++ 運算符或 Map.++() 方法來連接兩個 Map,Map 合併時會移除重複的 key。

輸出 Map 的 keys 和 values

以下通過 foreach 循環輸出 Map 中的 keys 和 values:

查看 Map 中是否存在指定的 Key

你可以使用 Map.contains 方法來查看 Map 中是否存在指定的 Key。

package main

import  scala.collection.mutable.Map

object mapScala {
  def main(args: Array[String]): Unit = {
    // 空哈希表,鍵爲字符串,值爲整型
    var A:Map[Char,Int] = Map()
    //添加
    A += ('I' -> 1)
    A += ('J' -> 5)
    A += ('K' -> 10)
    A += ('L' -> 100)
    //
    // Map 鍵值對演示
    val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

    println( "colors 中的鍵爲 : " + colors.keys )
    println( "colors 中的值爲 : " + colors.values )
    println( "檢測 colors 是否爲空 : " + colors.isEmpty )

    val nums: Map[Int, Int] = Map()
    println( "檢測 nums 是否爲空 : " + nums.isEmpty )

    val colors1 = Map("red" -> "#FF0000",
      "azure" -> "#F0FFFF",
      "peru" -> "#CD853F")
    val colors2 = Map("blue" -> "#0033FF",
      "yellow" -> "#FFFF00",
      "red" -> "#FF0000")

    //  ++ 作爲運算符
    var colors3 = colors1 ++ colors2
    println( "colors1 ++ colors2 : " + colors3 )

    //  ++ 作爲方法
    colors3 = colors1.++(colors2)
    println( "colors1.++(colors2) : " + colors3 )

    //
    val sites = Map("runoob" -> "http://www.runoob.com",
      "baidu" -> "http://www.baidu.com",
      "taobao" -> "http://www.taobao.com")

    sites.keys.foreach{ i =>
      print( "Key = " + i )
      println(" Value = " + sites(i) )}
    //如果 Map 中存在指定 key,返回 true,否則返回 false
    if( sites.contains( "runoob" )){
      println("runoob 鍵存在,對應的值爲 :"  + sites("runoob"))
    }else{
      println("runoob 鍵不存在")
    }
    if( sites.contains( "baidu" )){
      println("baidu 鍵存在,對應的值爲 :"  + sites("baidu"))
    }else{
      println("baidu 鍵不存在")
    }
    if( sites.contains( "google" )){
      println("google 鍵存在,對應的值爲 :"  + sites("google"))
    }else{
      println("google 鍵不存在")
    }
  }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章