scala map的經常使用操做

 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 }
相關文章
相關標籤/搜索