1 package cn.scala_base
2
3 /**
4 * map常用操作
5 */
6 object Map {
7
8 def main(args: Array[String]): Unit = {
9
10 //1.不可变map(有序)
11 val map1 = scala.collection.immutable.Map("wyc"->30,"tele"->20,"yeye"->100,"haha"->1000);
12 println(map1("wyc"));
13 println("map1---" + map1);
14
15 //error
16 // map1("wyc")=100;
17
18
19
20 //2. 可变map
21 val map2 = scala.collection.mutable.Map("wyc"->30,"tele"->20,"yeye"->100);
22 map2("wyc")=10000;
23 println(map2("wyc"));
24
25
26 val map3 = scala.collection.mutable.Map(("wyc",100),("tele",1000),("yeye",10000));
27 println(map3("wyc"));
28
29
30 //3.创建HashMap(无序)
31 val hashMap = new scala.collection.mutable.HashMap[String,Int];
32
33
34 //为map增加元素
35 hashMap += ("wyc"->1);
36 println(hashMap("wyc"))
37
38
39 //移除元素
40 hashMap -= "wyc";
41
42
43 //检查key是否存在
44 if(hashMap.contains("wyc")) println(hashMap("wyc")) else println(0);
45
46 //使用getOrElse进行检查
47 println(hashMap.getOrElse("wyc","不存在"));
48
49
50 //根据key进行排序的SortedMap,注意是immutable
51 val sortedMap = scala.collection.immutable.SortedMap("wyc"->100,"tele"->1000);
52 println("sortedMap----" + sortedMap);
53
54
55 //有序的LinkedHashMap
56 val linkedHashMap = scala.collection.mutable.LinkedHashMap("wyc"->100,"tele"->1000);
57 println("linkedHashMap----" + linkedHashMap);
58
59
60
61
62 //对于不可变的map1进行更新,其实是返回新的不可变map
63 val mapX = map1 + ("newEntry"->1);
64 val mapY = map1 - "wyc";
65
66
67 //遍历Map
68 for((key,value)<- map3) {
69 println(key + ":" + value);
70 }
71
72 for(key <- map3.keySet) {
73 println(key + ":" + map3(key));
74 }
75
76 //只遍历values
77 /*for(value<-map3.values) {
78 println(value);
79 }*/
80
81
82 //反转key与value
83 val reverseMap = for((key,value)<-map3) yield (value,key);
84 for(key<- reverseMap.keySet) {
85 println(key + ":" + reverseMap(key));
86 }
87
88 }
89
90
91 }