Scala学习笔记09【Map、Tuple、Zip常用操作实战】

Map

构建不可变Map

val map = Map("book" -> 10, "gun" -> 18, "ipad" -> 1000)
  for((k ,v) <- map) yield(k, v * 0.9)

//res1: scala.collection.immutable.Map[String,Double] = Map(book -> 9.0, gun -> 16.2, ipad -> 900.0)

构建可变Map

val scores = scala.collection.mutable.Map("Scala" -> 7, "Hadoop" -> 8, "Spark" -> 10)
scores   //=>Map(Hadoop -> 8, Spark -> 10, Scala -> 7)

通过key获取value的值,若不存在返回0

val hadoopScore = scores.getOrElse("Hadoop", 0)  
//=>hadoopScore: Int = 8

添加元素

scores += ("R" -> 9) 
//=>Map(Hadoop -> 8, R -> 9, Spark -> 10, Scala -> 7)

删除元素

scores -= "Hadoop"   //=>Map(R -> 9, Spark -> 10, Scala -> 7)

根据key排序

val sortedScore = scala.collection.immutable.SortedMap("Scala" -> 7, "Hadoop" -> 8, "Spark" -> 10)
sortedScore    //=>Map(Hadoop -> 8, Scala -> 7, Spark -> 10)

Tuple

基本定义:

val tuple = (1,2,3.14, "Jay", "Scala") //=>(1,2,3.14,Jay,Scala)

值的获取:

val third = tuple._3 //=> 3.14

返回Tuple中的值:

val(first, second, third, fourth, fifth) = tuple
/*
first: Int = 1
second: Int = 2
third: Double = 3.14
fourth: String = Jay
fifth: String = Scala
*/

选择性返回值, _占位符:

val(f, s, _, _, _) = tuple
/* f: Int = 1 s: Int = 2 */

判断是否大写, 大写放进一个集合,其余一个集合:

"Jay Scala".partition(_.isUpper) //=> (String, String) = (JS,ay cala)

Zip操作

zip函数将传进来的两个参数中相应位置上的元素组成一个pair数组。
如果其中一个参数元素比较长,那么多余的参数会被删掉。

val symbols = Array("[", "-", "]")  //=>Array[String] = Array([, -, ])

val counts = Array(2, 5, 2)   //=>Array[Int] = Array(2, 5, 2)

//组成一个pair数组
val pairs = symbols.zip(counts) //=>Array[(String, Int)] = Array(([,2), (-,5), (],2))

//打印y个x
for((x, y) <- pairs) print(x*y) //[[-----]]

你可能感兴趣的:(scala,map,zip,Tuple)