|NO.Z.00066|——————————|BigDataEnd|——|Hadoop&Scala.V05|——|Scala.v05|集合|集合常用算子|
一、map、foreach & mapValues
### --- map、foreach & mapValues
~~~ 集合对象都有 foreach、map 算子。
~~~ 两个算子的共同点在于:都是用于遍历集合对象,并对每一项执行指定的方法;
~~~ 两个算子的差异点在于:
~~~ foreach无返回值(准确说返回void),用于遍历集合
~~~ map返回集合对象,用于将一个集合转换成另一个集合
### --- 编程示例
~~~ 使用 foreach 打印集合元素
val numlist = (1 to 10).toList
numlist.foreach(elem=>print(elem+" "))
numlist.foreach(print _)
numlist.foreach(print)
~~~ 使用 map 对集合进行转换
numlist.map(_ > 2)
numlist.map(_ * 2)
### --- 操作 Map集合时,mapValues用于遍历value,是map操作的一种简化形式;
// Range(20, 0, -2)用给定的步长值设定一个范围,从开始到结束(不包含)。
//Map(20 -> 0,18 -> 1,16 -> 2,14 -> 3,12 -> 4,10 -> 5,8 -> 6,6 -> 7,4 -> 8,2 ->9)
val map = Range(20, 0, -2).zipWithIndex.toMap
// 将map集合中的value值+100
map.map(elem => (elem._1, elem._2 + 100))
map.map{case (k,v) => (k, v+100)}
// mapValues的表达最简洁
map.mapValues(_+100)
二、flatten & flatMap
### --- flatten & flatMap
~~~ flatten的作用是把嵌套的结构展开,把结果放到一个集合中;
~~~ 在 flatMap 中传入一个函数,该函数对每个输入都返回一个集合(而不是一个元素),
~~~ 最后把生成的多个集合“拍扁”成为一个集合;
### --- 编程示例
scala> val lst1 = List(List(1,2), List(3,4))
lst1: List[List[Int]] = List(List(1, 2), List(3, 4))
scala> lst1.flatten
res5: List[Int] = List(1, 2, 3, 4)
// flatten 把一个字符串的集合展开为一个字符集合,因为字符串本身就是字符的集合
scala> val lst4 = List("Java", "hadoop")
lst4: List[String] = List(Java, hadoop)
scala> lst4.flatten
res8: List[Char] = List(J, a, v, a, h, a, d, o, o, p)
// flatten 有效的处理 Some 和 None 组成的集合。它可以展开Some元素形成一个新的集合,同时去掉None元素
scala> val x = Array(Some(1), None, Some(3), None)
x: Array[Option[Int]] = Array(Some(1), None, Some(3), None)
// 方法很多,flatten最简单
scala> x.flatten
res9: Array[Int] = Array(1, 3)
scala> x.collect{case Some(i) => i}
res10: Array[Int] = Array(1, 3)
scala> x.filter(!_.isEmpty).map(_.get)
res11: Array[Int] = Array(1, 3)
// 下面两条语句等价
val lst = List(List(1,2,5,6),List(3,4))
// 将 lst 中每个元素乘2,最后作为一个集合返回
// 此时 flatMap = flatten + map
//List(1,2,5,6,3,4)
lst.flatten.map(_*2)
lst.flatMap((x: List[Int]) => x.map(_*2))
lst.flatMap(_.map(_*2))
// 将字符串数组按空格切分,转换为单词数组
~~~ 备注:flatMap = flatten + map 或 flatMap = map + flatten
val lines = Array("Apache Spark has an advanced DAG execution engine", "Spark offers over 80 high-level operators")
// 下面两条语句效果等价
//map算子产生的结果:Array(Array(Apache, Spark, has, an, advanced, DAG, execution,engine), Array(Spark, offers, over, 80, high-level, operators))
// flatten算子产生的结果:Array(Apache, Spark, has, an, advanced, DAG, execution,
engine, Spark, offers, over, 80, high-level, operators)
lines.map(_.split(" ")).flatten
// 此时 flatMap = map + flatten
lines.flatMap(_.split(" "))
三、collect
### --- collect
~~~ collect通过执行一个并行计算(偏函数),得到一个新的数组对象
### --- 编程示例
object CollectDemo {
//通过下面的偏函数,把chars数组的小写a转换为大写的A
val fun: PartialFunction[Char, Char] = {
case 'a' => 'A'
case x => x
}
def main(args: Array[String]): Unit = {
val chars = Array('a', 'b', 'c')
val newchars = chars.collect(fun)
println("newchars:" + newchars.mkString(","))
}
}
四、reduce
### --- reduce
~~~ reduce可以对集合当中的元素进行归约操作;
~~~ 还有 reduceLeft 和 reduceRight ,reduceLeft 从左向右归约,reduceRight 从右向左归约;
### --- 编程示例
val lst1 = (1 to 10).toList
lst1.reduce(_+_)
// 为什么这里能出现两个占位符?
lst1.reduce(_+_)
// 我们说过一个占位符代表一个参数,那么两个占位符就代表两个参数。根据这个思路改写等价的语句
// x类似于buffer,缓存每次操作的数据;y每次操作传递新的集合元素
lst1.reduce((x, y) => x + y)
// 利用reduce操作,查找 lst1 中的最大值
lst1.reduce((x,y) => if (x>y) x else y)
// reduceLeft、reduceRight
lst1.reduceLeft((x,y) => if (x>y) x else y)
lst1.reduceRight((x,y) => if (x>y) x else y)
五、sorted sortwith & sortby
### --- sorted sortwith & sortby
~~~ Scala中对于集合的排序有三种方法:sorted、sortBy、sortWith
### --- 编程示例
object SortDemo {
def main(args: Array[String]): Unit = {
val list = List(1, 9, 3, 8, 5, 6)
//sorted方法对一个集合进行自然排序
//sorted源码:def sorted[B >: A](implicit ord: Ordering[B]): Repr
//源码中有两点值得注意的地方:
// 1.sorted方法中有个隐式参数ord: Ordering。
// 2.sorted方法真正排序的逻辑是调用的java.util.Arrays.sort
val numSort: List[Int] = list.sorted
println(numSort)
//sortBy源码:def sortBy[B](f: A => B)(implicit ord: Ordering[B]): Repr = sorted(ord on f)
//sortBy最后调用的sorted方法
println(list.sortBy(x => x).reverse)
//sortWith源码:def sortWith(lt: (A, A) => Boolean): Repr = sorted(Ordering fromLessThan lt)
print(list.sortWith(_ > _))
}
}
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
——W.S.Landor
分类:
bdv015-scala
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」