Latest web development tutorials

Scala Map (map)

Scala collections Scala collections

Map (map) is a kind of iterative key-value pairs (key / value) structure.

All values ​​can be retrieved by a key.

Map the key is unique.

Map is also called a hash table (Hash tables).

Map There are two types of variable and can not be changed, except that the variable object can modify it without mutable objects can not.

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

In Scala you can use variable and immutable Map, direct use Map immutable, mutable use mutable.Map. The following example demonstrates the application of immutable Map:

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

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

When you define a Map, you need to define the type of key-value pairs. If you need to add key-value pairs, you can use the + sign, as follows:

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

Basic Operations Map

Scala Map There are three basic operations:

method description
keys Back Map all the keys (key)
values Map Returns all the values ​​(value)
isEmpty In the Map is empty Returns true

Examples

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

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

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

      println( "colors 中的键为 : " + colors.keys )
      println( "colors 中的值为 : " + colors.values )
      println( "检测 colors 是否为空 : " + colors.isEmpty )
      println( "检测 nums 是否为空 : " + nums.isEmpty )
   }
}

Implementation of the above code, the output is:

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

Map merger

You can use the++ operator or Map. ++ ()Method to connect two Map, removes duplicate key when Map merger. The following two examples demonstrate the combined Map:

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

      //  ++ 作为运算符
      var colors = colors1 ++ colors2
      println( "colors1 ++ colors2 : " + colors )

      //  ++ 作为方法
      colors = colors1.++(colors2)
      println( "colors1.++(colors2)) : " + colors )

   }
}

Implementation of the above code, the output 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)

Map of output keys and values

The following foreach loop through output Map of keys and values:

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

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

Implementation of the above code, the output is:

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

Check whether the specified Key exists in the Map

You can useMap.contains method to see if the presence of the specified Key Map.Examples are as follows:

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

      if( sites.contains( "w3big" )){
           println("w3big 键存在,对应的值为 :"  + sites("w3big"))
      }else{
           println("w3big 键不存在")
      }
      if( sites.contains( "baidu" )){
           println("baidu 键存在,对应的值为 :"  + sites("baidu"))
      }else{
           println("baidu 键不存在")
      }
      if( sites.contains( "google" )){
           println("google 键存在,对应的值为 :"  + sites("google"))
      }else{
           println("google 键不存在")
      }
   }
}

Implementation of the above code, the output is:

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

Scala Map method

The following table lists the commonly used methods Scala Map:

No. Method and Description
1

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

It returns a new Map, New Map xs composition

2

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

Returns a new Map, remove the key to elem1, elem2 or other elems.

3

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

Returns a new Map, remove xs object corresponding key

4

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

Returns the value of the specified key

5

def iterator: Iterator [(A, B)]

Create a new iterator, and outputs the key / value pair

6

def addString (b: StringBuilder): StringBuilder

The Map all the elements attached to the StringBuilder, can be added to a separator

7

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

The Map all the elements attached to the StringBuilder, can be added to a separator

8

def apply (key: A): B

Returns the value of the specified key, if there is no return to the default method Map

9

def clear (): Unit

Clear Map

10

def clone (): Map [A , B]

From one to another Map Map

11

def contains (key: A): Boolean

If there is a specified key Map, returns true, otherwise returns false.

12

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

Copy set to an array

13

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

Calculate the number of elements that meet the specified criteria set

14

def default (key: A): B

The default value is defined Map returns when the key is not present.

15

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

The new collection before returning discards n elements

16

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

Back discard the last n elements of the new collection

17

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

Discard element left to right, until the condition is not satisfied p

18

def empty: Map [A, B ]

Return the same type of empty Map

19

def equals (that: Any): Boolean

If the two are equal Map (key / value are equal), returns true, false otherwise

20

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

Analyzing the conditions specified in the collection element exists

twenty one

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

Back to all collections that meet the specified criteria

twenty two

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

Returns immutable Map meet the specified criteria of

twenty three

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

Finding the first element in the collection that meets the specified criteria

twenty four

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

All elements of the function to the set

25

def init: Map [A, B ]

Returns all elements, except the last one

26

def isEmpty: Boolean

Detecting whether the Map is empty

27

def keys: Iterable [A]

Return all key / p>

28

def last: (A, B)

Returns the last element

29

def max: (A, B)

Find the maximum element

30

def min: (A, B)

Find the smallest element

31

def mkString: String

The set of all elements of the display as a string

32

def product: (A, B)

Returns a collection of digital elements in the plot.

33

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

Removes the specified key

34

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

If they meet the condition returns true

35

def size: Int

Returns the number of elements in Map

36

def sum: (A, B)

Returns a collection of all the elements of the digital

37

def tail: Map [A, B ]

Returns a collection of other elements 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]

n elements Back

40

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

Returns elements specified condition is met

41

def toArray: Array [(A, B)]

Set transfer array

42

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

Back buffer, containing all the elements of the Map

43

def toList: List [A]

Back List, contains all the elements of the Map

44

def toSeq: Seq [A]

Back Seq, contains all the elements Map

45

def toSet: Set [A]

Back Set, containing all the elements of the Map

46

def toString (): String

Returns a String object

More ways to refer to the API documentation

Scala collections Scala collections