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
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)
把里面每一个元素拿过来作为映射,而且映射得到的结果是一对多的映射。
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的二元函数
归约操作有左右之分
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