Scala入门到精通——第四节 Set、Map、Tuple、队列操作实战

来源:互联网 发布:遗传算法的步骤 编辑:程序博客网 时间:2024/05/18 00:41

本节主要内容

  1. mutable、immutable集合
  2. Set操作实战
  3. Map操作实战
  4. Tuple操作实战
  5. 队列操作实战
  6. 栈操作实战

mutable、immutable集合

以下内容来源于Scala官方文档:
http://www.scala-lang.org/docu/files/collections-api/collections.html

Scala collections systematically distinguish between mutable and immutable collections. A mutable collection can be updated or extended in place. This means you can change, add, or remove elements of a collection as a side effect. Immutable collections, by contrast, never change. You have still operations that simulate additions, removals, or updates, but those operations will in each case return a new collection and leave the old collection unchanged.//大致意思是:scala中的集合分为两种,一种是可变的集合,另一种是不可变的集合//可变的集合可以更新或修改,添加、删除、修改元素将作用于原集合//不可变集合一量被创建,便不能被改变,添加、删除、更新操作返回的是新的集合,老集合保持不变
  • 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(集)是一种不存在重复元素的集合,它与数学上定义的集合是对应的

//定义一个集合//这里使用的是mutablescala> val numsSet=Set(3.0,5)numsSet: scala.collection.mutable.Set[Double] = Set(5.0, 3.0)//向集中添加一个元素,同前一讲中的列表和数组不一样的是//,Set在插入元素时并不保元素的顺序//默认情况下,Set的实现方式是HashSet实现方式,//集中的元素通过HashCode值进行组织scala> numsSet+6res20: scala.collection.mutable.Set[Double] = Set(5.0, 6.0, 3.0)//遍历集scala> for ( i <- res20 ) println(i)5.06.03.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+6res26: scala.collection.mutable.LinkedHashSet[Double] = Set(3.0, 5.0, 6.0)
  • 1

Map操作实战

Map是一种键值对的集合,一般将其翻译为映射

//直接初始化// ->操作符,左边是key,右边是valuescala> val studentInfo=Map("john" -> 21, "stephen" -> 22,"lucy" -> 20)studentInfo: scala.collection.immutable.Map[String,Int] = Map(john -> 21, stephen -> 22, lucy -> 20)//immutable不可变,它不具有以下操作scala> studentInfo.clear()<console>:10: error: value clear is not a member of scala.collection.immutable.Map[String,Int]              studentInfo.clear()                          ^//创建可变的Mapscala> val studentInfoMutable=scala.collection.mutable.Map("john" -> 21, "stephen" -> 22,"lucy" -> 20)studentInfoMutable: scala.collection.mutable.Map[String,Int] = Map(john -> 21, lucy -> 20, stephen -> 22)//mutable Map可变,比如可以将其内容清空scala> studentInfoMutable.clear()scala> studentInfoMutableres3: scala.collection.mutable.Map[String,Int] = Map()//遍历操作1scala> for( i <- studentInfoMutable ) println(i)(john,21)(lucy,20)(stephen,22)//遍历操作2scala> studentInfoMutable.foreach(e=>{val (k,v)=e; println(k+":"+v)})john:21lucy:20stephen:22//遍历操作3scala> studentInfoMutable.foreach(e=> println(e._1+":"+e._2))john:21lucy:20stephen:22//定义一个空的Mapscala> 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> xMapres13: 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" -> 1res18: (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._1res25: String = Helloscala> tuple._2res26: String = Chinascala> tuple._3res27: Int = 1//通过模式匹配获取元组内容scala> val (first, second, third)=tuplefirst: String = Hellosecond: String = Chinathird: Int = 1
  • 1

队列操作实战

//immutable queuescala> var queue=scala.collection.immutable.Queue(1,2,3)queue: scala.collection.immutable.Queue[Int] = Queue(1, 2, 3)//出队scala> queue.dequeueres38: (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 queuescala> 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 += 5res43: 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 Stackscala> import scala.collection.mutable.Stackimport 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.topres55: Int = 1//入栈scala> stack.push(1)res57: stack.type = Stack(1)//入栈scala> stack.push(2)res58: stack.type = Stack(2, 1)//出栈scala> stack.topres59: Int = 2scala> stackres60: scala.collection.mutable.Stack[Int] = Stack(2, 1)
阅读全文
0 0