Scala针对容器的操作(遍历映射过滤归约)案例
Posted 上课不要睡觉了
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Scala针对容器的操作(遍历映射过滤归约)案例相关的知识,希望对你有一定的参考价值。
Scala针对容器的操作(遍历、映射)
一、遍历操作
Scala容器的标准遍历方法foreach
def foreach[U](f:Elem => U) :Unit
object foreach_test
def main(args: Array[String]): Unit =
val list = List(1,2,3)
val f=(i:Int)=>println(i)
list.foreach(f)
val university = Map("XMU" -> "Xiamen University", "THU" -> "Tsinghua University", "PKU"
-> "Peking University")
university foreach (kv => println(kv._1 + ":" + kv._2))
university foreach x => x match case (k, v) => println(k + ":" + v)
//case (k,v)使用元组对象
university foreach case (k, v) => println(k + ":" + v)
out:
1
2
3
XMU:Xiamen University
THU:Tsinghua University
PKU:Peking University
二、映射操作
2.1.map方法
map用于对容器或者集合做一对一映射。
实例:
object map_test
def main(args: Array[String]): Unit =
val books=List("Hadoop","Hive","HDFS")
println(books.map(s=>s.toUpperCase()))
//toUpperCase方法将一个字符串中的每个字母都变成大写字母
println(books.map(s=>s.length))//将字符串映射到它的长度
out:
List(HADOOP, HIVE, HDFS)
List(6, 4, 4)
2.2.flatmap方法
把里面每一个元素拿过来作为映射,而且映射得到的结果是一对多的映射。
object map_test
def main(args: Array[String]): Unit =
val books=List("Hadoop","Hive","HDFS")
println(books flatMap(s=>s.toList))//中缀表示法
out:
List(H, a, d, o, o, p, H, i, v, e, H, D, F, S)
三、过滤操作
filter字符过滤
object filter_test
def main(args: Array[String]): Unit =
val university = Map(
"XMU" -> "Xiamen University",
"THU" -> "Tsinghua University",
"PKU" -> "Peking University",
"XMUT" -> "Xiamen University of Technology"
)
val xmus = university filter kv => kv._2 contains "Xiamen"
println(xmus)
out:
Map(XMU -> Xiamen University, XMUT -> Xiamen University of Technology)
整型过滤
val l = List(1, 2, 3, 4, 5, 6) filter _ % 2 == 0
println(l)
out:
List(2, 4, 6)
四、归约操作
reduce(f)
object reduce_test
def main(args: Array[String]): Unit =
val list = List(1, 2, 3, 4, 5)
val list_add = list.reduce(_ + _) //将列表元素累加,使用了占位符语法
println(list_add)
val list_mul = list.reduce(_ * _) //将列表元素连乘
println(list_mul)
val process = list map (_.toString) reduce ((x, y) => s"f($x,$y)")
println(process)
out:
15
120
f(f(f(f(1,2),3),4),5)
//f表示传入reduce的二元函数
归约操作有左右之分
- reduceLeft
- reduceRight
object reduce_test
def main(args: Array[String]): Unit =
val list = List(1, 2, 3, 4, 5)
val left1=list reduceLeft_-_
println(left1)
val right1=list reduceRight_-_
println(right1)
out:
-13
3
fold
scala> val list = List(1, 2, 3, 4, 5)
list: List[Int] = List(1, 2, 3, 4, 5)
scala> list.fold(10)(_*_)
res0: Int = 1200
scala> (list fold 10)(_*_)//fold的中缀调用写法
res1: Int = 1200
scala> (list foldLeft 10)(_-_)//计算顺序(((((10-1)-2)-3)-4)-5)
res2: Int = -5
以上是关于Scala针对容器的操作(遍历映射过滤归约)案例的主要内容,如果未能解决你的问题,请参考以下文章
大数据技术之_16_Scala学习_08_数据结构(下)-集合操作+模式匹配