目录

Scala Maps

Scala映射是键/值对的集合。 可以根据其键检索任何值。 键在Map中是唯一的,但值不必是唯一的。 地图也称为哈希表。 地图有两种,一种是immutable ,另一种是mutable 。 可变对象和不可变对象之间的区别在于,当对象是不可变的时,对象本身不能被更改。

默认情况下,Scala使用不可变映射。 如果要使用可变映射,则必须显式导入scala.collection.mutable.Map类。 如果要同时使用可变和不可变映射,则可以继续将不可变映射称为Map但可以将可变集称为mutable.Map

以下是声明不可变映射的示例语句 -

// Empty hash table whose keys are strings and values are integers:
var A:Map[Char,Int] = Map()
// A map with keys and values.
val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF")

在定义空映射时,类型注释是必需的,因为系统需要为变量分配具体类型。 如果我们想要为Map添​​加键值对,我们可以使用operator +,如下所示。

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

MAP的基本操作

地图上的所有操作都可以用以下三种方法表示。

Sr.No 方法和描述
1

keys

此方法返回包含地图中每个键的iterable。

2

values

此方法返回包含地图中每个值的iterable。

3

isEmpty

如果映射为空,则此方法返回true,否则返回false。

尝试以下示例程序,显示Map方法的用法。

例子 (Example)

object Demo {
   def main(args: Array[String]) {
      val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
      val nums: Map[Int, Int] = Map()
      println( "Keys in colors : " + colors.keys )
      println( "Values in colors : " + colors.values )
      println( "Check if colors is empty : " + colors.isEmpty )
      println( "Check if nums is empty : " + nums.isEmpty )
   }
}

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

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

Keys in colors : Set(red, azure, peru)
Values in colors : MapLike(#FF0000, #F0FFFF, #CD853F)
Check if colors is empty : false
Check if nums is empty : true

连接地图

您可以使用++运算符或Map.++()方法来连接两个或多个Maps,但在添加Maps时,它将删除重复的键。

尝试以下示例程序来连接两个Maps。

例子 (Example)

object Demo {
   def main(args: Array[String]) {
      val colors1 = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
      val colors2 = Map("blue" -> "#0033FF", "yellow" -> "#FFFF00", "red" -> "#FF0000")
      // use two or more Maps with ++ as operator
      var colors = colors1 ++ colors2
      println( "colors1 ++ colors2 : " + colors )
      // use two maps with ++ as method
      colors = colors1.++(colors2)
      println( "colors1.++(colors2)) : " + colors )
   }
}

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

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

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)

从地图打印键和值

您可以使用“foreach”循环遍历Map的键和值。 在这里,我们使用与迭代器关联的方法foreach来遍历键。 以下是示例程序。

例子 (Example)

object Demo {
   def main(args: Array[String]) {
      val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF","peru" -> "#CD853F")
      colors.keys.foreach{ i =>  
         print( "Key = " + i )
         println(" Value = " + colors(i) )}
   }
}

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

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

Key = red Value = #FF0000
Key = azure Value = #F0FFFF
Key = peru Value = #CD853F

检查地图中的密钥

您可以使用Map.contains方法来测试地图中是否存在给定的键。 尝试以下示例程序进行密钥检查。

例子 (Example)

object Demo {
   def main(args: Array[String]) {
      val colors = Map("red" -> "#FF0000", "azure" -> "#F0FFFF", "peru" -> "#CD853F")
      if( colors.contains( "red" )) {
         println("Red key exists with value :"  + colors("red"))
      } else {
           println("Red key does not exist")
      }
      if( colors.contains( "maroon" )) {
         println("Maroon key exists with value :"  + colors("maroon"))
      } else {
         println("Maroon key does not exist")
      }
   }
}

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

Command

\>scalac Demo.scala
\>scala Demo

输出 (Output)

Red key exists with value :#FF0000
Maroon key does not exist

Scala地图方法

以下是您在使用地图时可以使用的重要方法。 有关可用方法的完整列表,请查看Scala的官方文档。

Sr.No 带描述的方法
1

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

返回包含此映射的映射和xs提供的映射的新映射。

2

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

返回包含此映射的所有映射的新映射,但具有等于elem1,elem2或任何elems的键的映射除外。

3

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

返回一个新映射,其中包含此映射的所有键/值映射,但带有等于来自可遍历对象xs的键的键的映射除外。

4

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

(可选)返回与键关联的值。

5

def iterator: Iterator[(A, B)]

在此映射的所有键/值对上创建新的迭代器

6

def addString(b: StringBuilder): StringBuilder

将此可收缩集合的所有元素追加到字符串构建器。

7

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

使用分隔符字符串将此可收缩集合的所有元素追加到字符串构建器。

8

def apply(key: A): B

返回与给定键关联的值,或者如果不存在,则返回映射的默认方法的结果。

9

def clear(): Unit

从地图中删除所有绑定。 此操作完成后,地图将为空。

10

def clone(): Map[A, B]

创建接收器对象的副本。

11

def contains(key: A): Boolean

如果此映射中存在键的绑定,则返回true,否则返回false。

12

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

将此可收缩集合的值复制到数组。 使用此可收缩集合的值填充给定的数组xs。

13

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

计算可收缩集合中满足谓词的元素数量。

14

def default(key: A): B

定义映射的默认值计算,在找不到键时返回。

15

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

返回除前n个元素之外的所有元素。

16

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

返回除最后n个之外的所有元素

17

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

删除满足谓词的元素的最长前缀。

18

def empty: Map[A, B]

返回相同类型的空映射。

19

def equals(that: Any): Boolean

如果两个映射包含完全相同的键/值,则返回true,否则返回false。

20

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

如果给定谓词p适用于此可收缩集合的某些元素,则返回true,否则返回false。

21

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

返回满足谓词的此可收缩集合的所有元素。

22

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

返回一个不可变映射,该映射仅包含此映射的键值对,其中键满足谓词p。

23

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

查找满足谓词的可收缩集合的第一个元素(如果有)。

24

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

将函数f应用于此可收缩集合的所有元素。

25

def init: Map[A, B]

返回除last之外的所有元素。

26

def isEmpty: Boolean

测试地图是否为空。

27

def keys: Iterable[A]

返回所有键的迭代器。

28

def last: (A, B)

返回最后一个元素。

29

def max: (A, B)

找到最大的元素。

30

def min: (A, B)

找到最小的元素。

31

def mkString: String

以字符串形式显示此可收缩集合的所有元素。

32

def product: (A, B)

返回此可收缩集合的所有元素相对于num中*运算符的乘积。

33

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

从此映射中移除键,返回先前与该键关联的值作为选项。

34

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

仅保留谓词p返回true的那些映射。

35

def size: Int

返回此地图中的元素数量。

36

def sum: (A, B)

返回此可收缩集合的所有元素与num中的+运算符的总和。

37

def tail: Map[A, B]

返回除第一个之外的所有元素。

38

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

返回前n个元素。

39

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

返回最后n个元素。

40

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

获取满足谓词的元素的最长前缀。

41

def toArray: Array[(A, B)]

将此可收缩集合转换为数组。

42

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

返回包含此映射的所有元素的缓冲区。

43

def toList: List[A]

返回包含此映射的所有元素的列表。

44

def toSeq: Seq[A]

返回包含此映射的所有元素的seq。

45

def toSet: Set[A]

返回包含此映射的所有元素的集合。

46

def toString(): String

返回对象的String表示形式。

↑回到顶部↑
WIKI教程 @2018