object InAction {
//不可变数组
val map = Map("book" -> 10, "gun" -> 18, "ipad" -> 100)
//> map : scala.collection.immutable.Map[String,Int] = Map(book -> 10, gun -> 18
//| , ipad -> 100)
//遍历,生产新的map,注意value的类型变化
for((k,v) <- map) yield (k, v * 0.9) //> res0: scala.collection.immutable.Map[String,Double] = Map(book -> 9.0, gun -
//| > 16.2, ipad -> 90.0)
//创建可变map
val scores = scala.collection.mutable.Map("scala" -> 1, "hadoop" -> 2, "spark" -> 3)
//> scores : scala.collection.mutable.Map[String,Int] = Map(spark -> 3, hadoop
//| -> 2, scala -> 1)
//getOrElse:获取不到则取第二个参数的值
val hadoopScore = scores.getOrElse("hadoop1", 0)
//> hadoopScore : Int = 0
//map的增删
scores += ("java" -> 4) //> res1: InAction.scores.type = Map(spark -> 3, hadoop -> 2, scala -> 1, java -
//| > 4)
scores -= "hadoop" //> res2: InAction.scores.type = Map(spark -> 3, scala -> 1, java -> 4)
//排序
val sortedScore = scala.collection.immutable.SortedMap("scala" -> 1, "hadoop" -> 2, "spark" -> 3)
//> sortedScore : scala.collection.immutable.SortedMap[String,Int] = Map(hadoop
//| -> 2, scala -> 1, spark -> 3)
//tuple:类型可以不同,下标从1开始
val tuple = (1,2,3,"hello", "world") //> tuple : (Int, Int, Int, String, String) = (1,2,3,hello,world)
val third = tuple._3 //> third : Int = 3
//tuple的接收,可使用占位符
val (first, second, thirda, fourth, fifth) = tuple
//> first : Int = 1
//| second : Int = 2
//| thirda : Int = 3
//| fourth : String = hello
//| fifth : String = world
val (f, s, t, _, _) = tuple //> f : Int = 1
//| s : Int = 2
//| t : Int = 3
//按大写小分区,partition参数是个布尔表达式
"Hello World".partition(_.isUpper) //> res3: (String, String) = (HW,ello orld)
//zip拉链操作,返回一个map
val symbols = Array("[", "-", "]") //> symbols : Array[String] = Array([, -, ])
val counts = Array(1, 2, 3) //> counts : Array[Int] = Array(1, 2, 3)
val pairs = symbols.zip(counts) //> pairs : Array[(String, Int)] = Array(([,1), (-,2), (],3))
for ((x, y) <- pairs) Console.print(x * y)
}scala基础8-map/tuple/zip进阶
最新推荐文章于 2024-04-14 22:24:06 发布
本文深入探讨了Scala中各种集合的使用方法,包括不可变与可变Map的操作、Tuple的使用技巧、字符串分区处理以及Array的Zip操作等。通过具体实例展示了如何进行遍历、增删元素、排序及组合等多种实用操作。
316

被折叠的 条评论
为什么被折叠?



