Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Scala Map

Scala Map

Scala Collections Scala Collections

Map is an iterable key/value pair structure.

All values can be retrieved through their keys.

Keys in a Map are unique.

A Map is also called a hash table.

There are two types of Map, mutable and immutable; the difference is that a mutable object can be modified while an immutable one cannot.

By default Scala uses immutable Map. If you need to use a mutable collection, you need to explicitly import import scala.collection.mutable.Map class

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



// Empty hash table, key is string, value is integer

var A:Map[Char,Int] = Map()



// Map key-value pair demonstration

val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

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



A += ('I' -> 1)

A += ('J' -> 5)

A += ('K' -> 10)

A += ('L' -> 100)


Basic Map 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 use 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: "

keys

)

      println

(

"The values in colors are: "

values

)

      println

(

"Check whether colors is empty: "

isEmpty

)

      println

(

"Check whether nums is empty: "

isEmpty

)

   

}

}

The output of the code above is:



$ scalac Test.scala 

$ scala Test

colors 中的键为 : Set(red, azure, peru)

colors 中的值为 : MapLike(#FF0000, #F0FFFF, #CD853F)

检测 colors 是否为空 : false

检测 nums 是否为空 : true


Merging Maps

You can use the ++ operator or the Map.++() method to concatenate two Maps; when merging Maps, 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 : "

)

     

// ++ as a method

      colors

=

colors1.++

(

colors2

)

      println

(

"colors1.++(colors2) : "

)

   

}

}

The output of the code above is:



$ 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)


Outputting 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

(

"runoob"

"http://www.runoob.com"

,

                       

"baidu"

"http://www.baidu.com"

,

                       

"taobao"

"http://www.taobao.com"

)

      sites.

keys

.

foreach

{

i

=>

 

                           print

(

"Key = "

)

                           println

(

" Value = "

(

i

)

)

}

   

}

}

The output of the code above is:



$ scalac Test.scala 

$ scala Test

Key = runoob Value = http://www.runoob.com

Key = baidu Value = http://www.baidu.com

Key = taobao Value = http://www.taobao.com


Checking whether a specified Key exists in a Map

You can use the Map.contains method to check whether a specified Key exists in a Map. Example as follows:

Example

object

Test

{

   

def

main

(

args

:

Array

[

String

]

)

{

     

val

sites

=

Map

(

"runoob"

"http://www.runoob.com"

,

                       

"baidu"

"http://www.baidu.com"

,

                       

"taobao"

"http://www.taobao.com"

)

     

if

(

sites.

contains

(

"runoob"

)

)

{

           println

(

"The key runoob exists, with value: "

 + sites

(

"runoob"

)

)

     

}

else

{

           println

(

"The key runoob does not exist"

)

     

}

     

if

(

sites.

contains

(

"baidu"

)

)

{

           println

(

"The key baidu exists, with value: "

 + sites

(

"baidu"

)

)

     

}

else

{

           println

(

"The key baidu does not exist"

)

     

}

     

if

(

sites.

contains

(

"google"

)

)

{

           println

(

"The key google exists, with value: "

 + sites

(

"google"

)

)

     

}

else

{

           println

(

"The key google does not exist"

)

     

}

   

}

}

The output of the code above is:



$ scalac Test.scala 

$ scala Test

runoob 键存在,对应的值为 :http://www.runoob.com

baidu 键存在,对应的值为 :http://www.baidu.com

google 键不存在


Scala Map Methods

The following table lists the commonly used methods of Scala Map:

No. Method and description
1

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

Returns a new Map consisting of the new Map and xs

2

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

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

3

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

Returns a new Map with the corresponding keys of the xs object removed

4

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

Returns the value of 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, optionally with a separator

7

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

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

8

def apply(key: A): B

Returns the value of the specified key, or the Map's default value if it does not exist

9

def clear(): Unit

Clears the Map

10

def clone(): Map[A, B]

Copies from one Map to another

11

def contains(key: A): Boolean

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

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 satisfying a specified condition

14

def default(key: A): B

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

15

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

Returns a new collection with the first n elements dropped

16

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

Returns a new collection with the last n elements dropped

17

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

Drops elements from left to right until predicate p no longer holds

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 keys and values), false otherwise

20

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

Determines whether elements satisfying a specified condition exist in the collection

21

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

Returns all elements satisfying a specified condition

22

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

Returns an immutable Map that satisfies a specified condition

23

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

Finds the first element in the collection satisfying a 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

Tests 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)

Finding 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 the 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 specified condition is satisfied

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 of a collection except the first

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 satisfying a specified condition

41

def toArray: Array[(A, B)]

Converts the collection to an 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 to API Documentation

Scala Collections Scala Collections