11.6 扫描(scan)
扫描,即对某个集合的所有元素做fold
操作,但是会把产生的所有中间结果放置于一个集合中保存
package com.atguigu.day11.operate
object ScanDemo1 {
def main(args: Array[String]): Unit = {
var list1 = List(10, 1, 3, 5, 8, 9, 22, 89)
// 返回的是一个保存中间结果的集合 100, 90, 89, 86,...
val list2: List[Int] = list1.scan(100)(minus)
println(list2)
val list3: List[Int] = list1.scanLeft(100)(minus)
println(list3)
val list4: List[Int] = list1.scanRight(100)(minus)
println(list4)
}
def minus(a: Int, b: Int) = {
a - b
}
}
练习1
val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD"
将sentence
中各个字符,通过foldLeft
存放到一个ArrayBuffer
中
package com.atguigu.day11.operate
import scala.collection.mutable.ArrayBuffer
object Test1 {
def main(args: Array[String]): Unit = {
val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD"
var arr:ArrayBuffer[Char] = new ArrayBuffer[Char]
sentence.foldLeft(arr)(putArray)
println(arr)
}
def putArray(arr: ArrayBuffer[Char], c: Char) : ArrayBuffer[Char]= {
arr.append(c)
arr
}
}
练习2:
val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD"
使用映射集合,统计一句话中,各个字母出现的次数
package com.atguigu.day11.operate
import scala.collection.mutable
object Test2 {
def main(args: Array[String]): Unit = {
// 统计每个字符出现的次数 A 3, B 10
val sentence = "AAAAAAAAAABBBBBBBBCCCCCDDDDDDD"
val map: mutable.Map[Char, Int] = mutable.Map[Char, Int]()
sentence.foldLeft(map)(charCount)
println(map)
}
def charCount(map: mutable.Map[Char, Int], c: Char) = {
map(c) = map.getOrElse(c, 0) + 1
map
}
}