Scala Map

Scala 集合Scala Collections

A Map is an iterable key/value structure.

All values can be obtained through keys.

Keys in a Map are unique.

A Map is also called a hash table.

Map has two types: mutable and immutable. The difference is that mutable objects can be modified, while immutable objects cannot.

By default, Scala uses immutable Map. If you need to use mutable collection, you need to explicitly importimport scala.collection.mutable.MapClass

In Scala, you can use both mutable and immutable Maps. For immutable, use Map directly; for mutable, use mutable.Map. The following example demonstrates the application of an immutable Map:

// 空哈希表,键为字符串,值为整型
var A:Map[Char,Int] = Map()

// Map 键值对演示
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

When defining a Map, you need to define types for key-value pairs. If you need to add key-value pairs, you can use the + sign, as shown below:

A += ('I' -> 1)
A += ('J' -> 5)
A += ('K' -> 10)
A += ('L' -> 100)

Map Basic Operations

Scala Map has three basic operations:

Method Description
keys Returns all keys of the Map
values Returns all values of the Map
isEmpty Returns true when the Map is empty

Example

The following example demonstrates the basic application of the above three methods:

Example

object Test {
   def main(args: Array[String]) {
      val colors = Map("red" -> "#FF0000",
                       "azure" -> "#F0FFFF",
                       "peru" -> "#CD853F")

      val nums: Map[Int, Int] = Map()

      println( "The keys in colors are: " + colors.keys )
      println( "The values in colors are: " + colors.values )
      println( "Check if colors is empty: " + colors.isEmpty )
      println( "Check if nums is empty: " + nums.isEmpty )
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
colors 中的键为 : Set(red, azure, peru)
colors 中的值为 : MapLike(#FF0000, #F0FFFF, #CD853F)
检测 colors 是否为空 : false
检测 nums 是否为空 : true

Map Merge

You can use++operator orMap.++()method to concatenate two Maps. When Maps are merged, duplicate keys are removed. The following demonstrates an example of merging two Maps:

Example

object Test {
   def main(args: Array[String]) {
      val colors1 = Map("red" -> "#FF0000",
                        "azure" -> "#F0FFFF",
                        "peru" -> "#CD853F")
      val colors2 = Map("blue" -> "#0033FF",
                        "yellow" -> "#FFFF00",
                        "red" -> "#FF0000")

      // ++ as an operator
      var colors = colors1 ++ colors2
      println( "colors1 ++ colors2 : " + colors )

      // ++ as a method
      colors = colors1.++(colors2)
      println( "colors1.++(colors2) : " + colors )

   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
colors1 ++ colors2 : Map(blue -> #0033FF, azure -> #F0FFFF, peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)
colors1.++(colors2) : Map(blue -> #0033FF, azure -> #F0FFFF, peru -> #CD853F, yellow -> #FFFF00, red -> #FF0000)

Output the keys and values of a Map

The following uses a foreach loop to output the keys and values in a Map:

Example

object Test {
   def main(args: Array[String]) {
      val sites = Map("example" -> "http://www.example.com",
                       "baidu" -> "http://www.baidu.com",
                       "taobao" -> "http://www.taobao.com")

      sites.keys.foreach{ i =>  
                           print( "Key = " + i )
                           println(" Value = " + sites(i) )}
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
Key = example Value = http://www.example.com
Key = baidu Value = http://www.baidu.com
Key = taobao Value = http://www.taobao.com

Check whether a Map contains a specified Key

You can useMap.containsmethod to check whether a specified Key exists in a Map. Example:

Example

object Test {
   def main(args: Array[String]) {
      val sites = Map("example" -> "http://www.example.com",
                       "baidu" -> "http://www.baidu.com",
                       "taobao" -> "http://www.taobao.com")

      if( sites.contains( "example" )){
           println("example key exists, corresponding value is:"  + sites("example"))
      }else{
           println("example key does not exist")
      }
      if( sites.contains( "baidu" )){
           println("baidu key exists, corresponding value is:"  + sites("baidu"))
      }else{
           println("baidu key does not exist")
      }
      if( sites.contains( "google" )){
           println("google key exists, corresponding value is:"  + sites("google"))
      }else{
           println("google key does not exist")
      }
   }
}

Executing the above code produces the following output:

$ scalac Test.scala 
$ scala Test
example 键存在,对应的值为 :http://www.example.com
baidu 键存在,对应的值为 :http://www.baidu.com
google 键不存在

Scala Map Methods

The following table lists common methods of Scala Map:

No. Method and Description
1

def ++(xs: Map[(A, B)]): Map[A, B]

Returns a new Map composed of the new Map xs

2

def -(elem1: A, elem2: A, elems: A*): Map[A, B]

Returns a new Map, removing keys elem1, elem2, or other elems.

3

def --(xs: GTO[A]): Map[A, B]

Returns a new Map, removing the corresponding keys in the xs object.

4

def get(key: A): Option[B]

Returns the value for the specified key

5

def iterator: Iterator[(A, B)]

Creates a new iterator and outputs key/value pairs

6

def addString(b: StringBuilder): StringBuilder

Appends all elements of the Map to a StringBuilder, with an optional separator

7

def addString(b: StringBuilder, sep: String): StringBuilder

Appends all elements of the Map to a StringBuilder, with an optional separator

8

def apply(key: A): B

Returns the value for the specified key, or the default method of the Map if it does not exist

9

def clear(): Unit

Clears the Map

10

def clone(): Map[A, B]

Copies from one Map to another Map

11

def contains(key: A): Boolean

Returns true if the specified key exists in the Map, otherwise returns false.

12

def copyToArray(xs: Array[(A, B)]): Unit

Copies the collection to an array

13

def count(p: ((A, B)) => Boolean): Int

Counts the number of collection elements that satisfy the specified condition

14

def default(key: A): B

Defines the default value of the Map, returned when the key does not exist.

15

def drop(n: Int): Map[A, B]

Returns a new collection after discarding the first n elements

16

def dropRight(n: Int): Map[A, B]

Returns a new collection after discarding the last n elements

17

def dropWhile(p: ((A, B)) => Boolean): Map[A, B]

Drops elements from left to right until condition p is false

18

def empty: Map[A, B]

Returns an empty Map of the same type

19

def equals(that: Any): Boolean

Returns true if two Maps are equal (both key/value equal), otherwise returns false

20

def exists(p: ((A, B)) => Boolean): Boolean

Determines whether an element satisfying the specified condition exists in the collection

21

def filter(p: ((A, B))=> Boolean): Map[A, B]

Returns all elements that satisfy the specified condition

22

def filterKeys(p: (A) => Boolean): Map[A, B]

Returns an immutable Map that meets the specified condition

23

def find(p: ((A, B)) => Boolean): Option[(A, B)]

Finds the first element in the collection that satisfies the specified condition

24

def foreach(f: ((A, B)) => Unit): Unit

Applies a function to all elements of the collection

25

def init: Map[A, B]

Returns all elements except the last one

26

def isEmpty: Boolean

Checks whether the Map is empty

27

def keys: Iterable[A]

Returns all keys

28

def last: (A, B)

Returns the last element

29

def max: (A, B)

Finds the largest element

30

def min: (A, B)

Finds the smallest element

31

def mkString: String

Displays all elements of the collection as a string

32

def product: (A, B)

Returns the product of numeric elements in the collection.

33

def remove(key: A): Option[B]

Removes the specified key

34

def retain(p: (A, B) => Boolean): Map.this.type

Returns true if the condition is met

35

def size: Int

Returns the number of elements in the Map

36

def sum: (A, B)

Returns the sum of all numeric elements in the collection

37

def tail: Map[A, B]

Returns all elements in a collection except the first element

38

def take(n: Int): Map[A, B]

Returns the first n elements

39

def takeRight(n: Int): Map[A, B]

Returns the last n elements

40

def takeWhile(p: ((A, B)) => Boolean): Map[A, B]

Returns elements that satisfy the specified condition

41

def toArray: Array[(A, B)]

Converts collection to array

42

def toBuffer[B >: A]: Buffer[B]

Returns a buffer containing all elements of the Map

43

def toList: List[A]

Returns a List containing all elements of the Map

44

def toSeq: Seq[A]

Returns a Seq containing all elements of the Map

45

def toSet: Set[A]

Returns a Set containing all elements of the Map

46

def toString(): String

Returns a string object

For more methods, refer toAPI documentation

Scala 集合Scala Collections

Other extensions