📜  Scala集合-HashMap

📅  最后修改于: 2020-11-02 04:30:40             🧑  作者: Mango


Scala映射是键/值对的集合。可以根据其键检索任何值。键在地图中是唯一的,但值不必是唯一的。 HashMap实现不可变的映射,并使用哈希表实现相同的映射。

声明HashMap变量

以下是用于声明HashMap变量的语法。

句法

val colors = HashMap("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")

在这里,颜色被声明为Strings,Int的哈希映射,它具有三个键值对。可以使用以下命令添加值-

命令

var myMap1: HashMap[Char, Int] = colors + ("black" -> "#000000");

处理HashMap

下面是一个示例程序,显示了如何创建,初始化和处理HashMap-

import scala.collection.immutable.HashMap
object Demo {
   def main(args: Array[String]) = {
      var myMap: HashMap[String,String] = HashMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      );
      // Add an element
      var myMap1: HashMap[String,String] = myMap + ("white" -> "#FFFFFF");
      // Print key values
      myMap.keys.foreach{ 
         i =>  
         print( "Key = " + i )
         println(" Value = " + myMap(i) )
      }
      if( myMap.contains( "red" )) {
         println("Red key exists with value :"  + myMap("red"))
      } else {
         println("Red key does not exist")
      }
      if( myMap.contains( "maroon" )) {
         println("Maroon key exists with value :"  + myMap("maroon"))
      } else {
         println("Maroon key does not exist")
      }
      //removing element
      var myMap2: HashMap[String,String] = myMap - ("white");
      // Create empty map
      var myMap3: HashMap[String,String] = HashMap.empty[String, String];
      println(myMap1);
      println(myMap2);
      println(myMap3);          
   }
}

将以上程序保存在Demo.scala中。以下命令用于编译和执行该程序。

命令

\>scalac Demo.scala
\>scala Demo

输出

Key = azure Value = #F0FFFF
Key = peru Value = #CD853F
Key = red Value = #FF0000
Red key exists with value :#FF0000
Maroon key does not exist
HashMap(azure -> #F0FFFF, peru -> #CD853F, white -> #FFFFFF, red -> #FF0000)
HashMap(azure -> #F0FFFF, peru -> #CD853F, red -> #FF0000)
HashMap()