English 中文(简体)
Scala Collections - ListMap
  • 时间:2024-12-22

Scala Collections - ListMap


Previous Page Next Page  

Scala map is a collection of key/value pairs. Any value can be retrieved based on its key. Keys are unique in the Map, but values need not be unique. ListMap implements immutable map and uses pst to implement the same. It is used with small number of elements.

Declaring ListMap Variables

The following is the syntax for declaring an ListMap variable.

Syntax


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

Here, colors is declared as an hash-map of Strings, Int which has three key-value pairs. Values can be added by using commands pke the following −

Command


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

Processing ListMap

Below is an example program of showing how to create, initiapze and process ListMap −

Example


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);		  
   }
}

Save the above program in Demo.scala. The following commands are used to compile and execute this program.

Command


>scalac Demo.scala
>scala Demo

Output


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()
Advertisements