📜  Scala集合-ListMap

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


Scala映射是键/值对的集合。可以根据其键检索任何值。键在地图中是唯一的,但值不必是唯一的。 ListMap实现不可变的映射,并使用list来实现相同的映射。它与少量元素一起使用。

声明ListMap变量

以下是声明ListMap变量的语法。

句法

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

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

命令

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

处理ListMap

以下是显示如何创建,初始化和处理ListMap的示例程序-

import scala.collection.immutable.ListMap

object Demo {
   def main(args: Array[String]) = {
      var myMap: ListMap[String,String] = ListMap(
         "red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F"
      );
      // Add an element
      var myMap1: ListMap[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: ListMap[String,String] = myMap - ("white");
      // Create empty map
      var myMap3: ListMap[String,String] = ListMap.empty[String, String];
      println(myMap1);
      println(myMap2);    
      println(myMap3);          
   }
}

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

命令

\>scalac Demo.scala
\>scala Demo

输出

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