Scala入门到精通——第四节 Set、Map、Tuple、队列操作实战
本節主要內容
mutable、immutable集合
以下內容來源于Scala官方文檔:
http://www.scala-lang.org/docu/files/collections-api/collections.html
- 1
scala中所有的集合都來自于scala.collection包及其子包mutable, immutable當中
//scala.collection.immutable包中的集合絕對是不可變的,函數式編程語言推崇使用immutable集合 A collection in package scala.collection.immutable is guaranteed to be immutable for everyone. Such a collection will never change after it is created. Therefore, you can rely on the fact that accessing the same collection value repeatedly at different points in time will always yield a collection with the same elements. //scala.collection.immutable包中的集合在是可變的,使用的時候必須明白集合何時發生變化 A collection in package scala.collection.mutable is known to have some operations that change the collection in place. So dealing with mutable collection means you need to understand which code changes which collection when.//scala.collection中的集合要么是mutalbe的,要么是immutable的 //同時該包中也定義了immutable及mutable集合的接口 A collection in package scala.collection can be either mutable or immutable. For instance, collection.IndexedSeq[T] is a superclass of both collection.immutable.IndexedSeq[T] and collection.mutable.IndexedSeq[T] Generally, the root collections in package scala.collection define the same interface as the immutable collections, and the mutable collections in package scala.collection.mutable typically add some side-effecting modification operations to this immutable interface.在scala中,默認使用的都是immutable集合,如果要使用mutable集合,需要在程序中引入
import scala.collection.mutable //由于immutable是默認導入的,因此要使用mutable中的集合的話 //使用如下語句 scala> val mutableSet=mutable.Set(1,2,3) mutableSet: scala.collection.mutable.Set[Int] = Set(1, 2, 3) //不指定的話,創建的是immutable 集合 scala> val mutableSet=Set(1,2,3) mutableSet: scala.collection.immutable.Set[Int] = Set(1, 2, 3)直接使用Set(1,2,3)創建的是immutable集合,這是因為當你不引入任何包的時候,scala會默認導入以幾個包:
Predef對象中包含了Set、Map等的定義
scala集合類的層次結構:
scala.collection包中的集合類層次結構如下圖:
These are all high-level abstract classes or traits, which generally have mutable as well as immutable implementations.
scala.collection.immutable包中的類層次結構:
scala.collection.mutable包中的類層次結構:
可變集合與不可變集合對應關系:
Set操作實戰
1 Set(集)是一種不存在重復元素的集合,它與數學上定義的集合是對應的
//定義一個集合 //這里使用的是mutable scala> val numsSet=Set(3.0,5) numsSet: scala.collection.mutable.Set[Double] = Set(5.0, 3.0)//向集中添加一個元素,同前一講中的列表和數組不一樣的是 //,Set在插入元素時并不保元素的順序 //默認情況下,Set的實現方式是HashSet實現方式, //集中的元素通過HashCode值進行組織 scala> numsSet+6 res20: scala.collection.mutable.Set[Double] = Set(5.0, 6.0, 3.0)//遍歷集 scala> for ( i <- res20 ) println(i) 5.0 6.0 3.0//如果對插入的順序有著嚴格的要求,則采用scala.collection.mutalbe.LinkedHashSet來實現 scala> val linkedHashSet=scala.collection.mutable.LinkedHashSet(3.0,5) linkedHashSet: scala.collection.mutable.LinkedHashSet[Double] = Set(3.0, 5.0)scala> linkedHashSet+6 res26: scala.collection.mutable.LinkedHashSet[Double] = Set(3.0, 5.0, 6.0)- 1
Map操作實戰
Map是一種鍵值對的集合,一般將其翻譯為映射
//直接初始化 // ->操作符,左邊是key,右邊是value scala> val studentInfo=Map("john" -> 21, "stephen" -> 22,"lucy" -> 20) studentInfo: scala.collection.immutable.Map[String,Int] = Map(john -> 21, stephe n -> 22, lucy -> 20)//immutable不可變,它不具有以下操作 scala> studentInfo.clear() <console>:10: error: value clear is not a member of scala.collection.immutable.M ap[String,Int]studentInfo.clear()^ //創建可變的Map scala> val studentInfoMutable=scala.collection.mutable.Map("john" -> 21, "stephe n" -> 22,"lucy" -> 20) studentInfoMutable: scala.collection.mutable.Map[String,Int] = Map(john -> 21, l ucy -> 20, stephen -> 22) //mutable Map可變,比如可以將其內容清空 scala> studentInfoMutable.clear()scala> studentInfoMutable res3: scala.collection.mutable.Map[String,Int] = Map()//遍歷操作1 scala> for( i <- studentInfoMutable ) println(i) (john,21) (lucy,20) (stephen,22)//遍歷操作2 scala> studentInfoMutable.foreach(e=> {val (k,v)=e; println(k+":"+v)} ) john:21 lucy:20 stephen:22 //遍歷操作3 scala> studentInfoMutable.foreach(e=> println(e._1+":"+e._2)) john:21 lucy:20 stephen:22//定義一個空的Map scala> val xMap=new scala.collection.mutable.HashMap[String,Int]() xMap: scala.collection.mutable.HashMap[String,Int] = Map()//往里面填充值 scala> xMap.put("spark",1) res12: Option[Int] = Nonescala> xMap res13: scala.collection.mutable.HashMap[String,Int] = Map(spark -> 1)//判斷是否包含spark字符串 scala> xMap.contains("spark") res14: Boolean = true//-> 初始化Map,也可以通過 ("spark",1)這種方式實現(元組的形式) scala> val xMap=scala.collection.mutable.Map(("spark",1),("hive",1)) xMap: scala.collection.mutable.Map[String,Int] = Map(spark -> 1, hive -> 1)scala> "spark" -> 1 res18: (String, Int) = (spark,1)//獲取元素 scala> xMap.get("spark") res19: Option[Int] = Some(1)scala> xMap.get("SparkSQL") res20: Option[Int] = None- 1
Option,None,Some類型
Option、None、Some是scala中定義的類型,它們在scala語言中十分常用,因此這三個類型非學重要。
None、Some是Option的子類,它主要解決值為null的問題,在Java語言中,對于定義好的HashMap,如果get方法中傳入的鍵不存在,方法會返回null,在編寫代碼的時候對于null的這種情況通常需要特殊處理,然而在實際中經常會忘記,因此它很容易引起 NullPointerException異常。在Scala語言中通過Option、None、Some這三個類來避免這樣的問題,這樣做有幾個好處,首先是代碼可讀性更強,當看到Option時,我們自然而然就知道它的值是可選的,然后變量是Option,比如Option[String]的時候,直接使用String的話,編譯直接通不過。
前面我們看到:
scala> xMap.get("spark") res19: Option[Int] = Some(1)那要怎么才能獲取到最終的結果呢,
//通過模式匹配得到最終的結果
scala> def show(x:Option[Int]) =x match{
| case Some(s) => s
| case None => “????”
| }
show: (x: Option[Int])Any
scala> show(xMap.get(“Spark”))
res21: Any = 1
scala> show(xMap.get(“sparkSQL”))
res22: Any = ????
元組操作實戰
前面我們提到Map是鍵值對的集合,元組則是不同類型值的聚集
//元組的定義 scala> ("hello","china","beijing") res23: (String, String, String) = (hello,china,beijing)scala> ("hello","china",1) res24: (String, String, Int) = (hello,china,1)scala> var tuple=("Hello","China",1) tuple: (String, String, Int) = (Hello,China,1)//訪問元組內容 scala> tuple._1 res25: String = Helloscala> tuple._2 res26: String = Chinascala> tuple._3 res27: Int = 1//通過模式匹配獲取元組內容 scala> val (first, second, third)=tuple first: String = Hello second: String = China third: Int = 1- 1
隊列操作實戰
//immutable queue scala> var queue=scala.collection.immutable.Queue(1,2,3) queue: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3)//出隊 scala> queue.dequeue res38: (Int, scala.collection.immutable.Queue[Int]) = (1,Queue(2, 3))//入隊 scala> queue.enqueue(4) res40: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3, 4)//mutable queue scala> var queue=scala.collection.mutable.Queue(1,2,3,4,5) queue: scala.collection.mutable.Queue[Int] = Queue(1, 2, 3, 4, 5)//入隊操作 scala> queue += 5 res43: scala.collection.mutable.Queue[Int] = Queue(1, 2, 3, 4, 5, 5)//集合方式 scala> queue ++= List(6,7,8) res45: scala.collection.mutable.Queue[Int] = Queue(1, 2, 3, 4, 5, 5, 6, 7, 8)棧操作實戰
//mutable Stack scala> import scala.collection.mutable.Stack import scala.collection.mutable.Stack//new 創建方式 scala> val stack = new Stack[Int] stack: scala.collection.mutable.Stack[Int] = Stack()//Apply創建方式 scala> val stack1=Stack(1,2,3) stack1: scala.collection.mutable.Stack[Int] = Stack(1, 2, 3)//出棧 scala> stack1.top res55: Int = 1//入棧 scala> stack.push(1) res57: stack.type = Stack(1) //入棧 scala> stack.push(2) res58: stack.type = Stack(2, 1) //出棧 scala> stack.top res59: Int = 2scala> stack res60: scala.collection.mutable.Stack[Int] = Stack(2, 1)總結
以上是生活随笔為你收集整理的Scala入门到精通——第四节 Set、Map、Tuple、队列操作实战的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 深入理解Spark 2.1 Core (
- 下一篇: Scala入门到精通——第五节 函数、高