当前位置:网站首页>scala减少,reduceLeft reduceRight,折叠,foldLeft foldRight
scala减少,reduceLeft reduceRight,折叠,foldLeft foldRight
2022-08-03 08:41:00 【But he that doeth good mo ask future】
1. 归约函数
1.1 reduce
聚合: N -> 1,如 sum函数统计List中所有元素的和; 在scalaThe bottom layer uses pairwise aggregation,The type of the aggregated result is ANDreduce方法的返回值类型相同
object T27 {
def main(args: Array[String]): Unit = {
val dataList = List(1, 2, 3, 4,5)
val i = dataList.reduce(_ - _)
println(i)
}
}
1.2 reduceLeft
从左往右,Performs an operator on the elements in the collection
object T28 {
def main(args: Array[String]): Unit = {
val dataList = List(1, 2, 3, 4,5)
val i = dataList.reduceLeft(_ - _)
println(i)
}
}
注:The operation logic is( ( ( (1 - 2) - 3) - 4) - 5),即 op( op( ... op(x_1, x_2) ..., x_{n-1}), x_n)
1.3 reduceRight
从右往左,Performs an operator on the elements in the collection
object T29 {
def main(args: Array[String]): Unit = {
val dataList = List(1, 2, 3, 4, 5)
val i = dataList.reduceRight(_ - _)
println(i)
}
}
注:The operation logic is(1 - (2 - (3 - (4 - 5) ) ) ),即 op(x_1, op(x_2, ..., op(x_{n-1}, x_n)...))
2. fold、foldLeft 、foldRight
fold函数的本质是Aggregate with the initial value and each piece of data in the collection;fold方法实际是函数柯里化,有2个参数,第一个参数表示初始值,The second parameter represents the calculation rule.foldThere are two variants of the method:foldLeft()和foldRight():foldLeft(),第一个参数为累计值,The direction in which the collection is traversed is 从左到右;foldRight(),第二个参数为累计值,The direction in which the collection is traversed is 从右到左
如:合并2个map并keyThe same summation
object T30 {
def main(args: Array[String]): Unit = {
val map1 = mutable.Map("a" -> 1, "b" -> 1, "c" -> 3)
val map2 = mutable.Map("a" -> 1, "d" -> 1, "c" -> 3)
map1.foldLeft(map2)((map, element) => {
val k = element._1
val v = element._2
val newV = map.getOrElse(k, 0) + v
map.update(k, newV)
map
})
println(map2)
}
}
边栏推荐
- Scala parallel collections, parallel concurrency, thread safety issues, ThreadLocal
- 并发之多把锁和活跃性
- 并发之ReentrantLock
- [Kaggle combat] Prediction of the number of survivors of the Titanic (from zero to submission to Kaggle to model saving and restoration)
- window的供选数据流
- LINGO 18.0 software installation package download and installation tutorial
- 并发之固定运行和交替运行方案
- 线性表
- 国内IT市场还有发展吗?有哪些创新好用的IT运维工具可以推荐?
- 使用pipreqs导出项目所需的requirements.txt(而非整个环境)
猜你喜欢
随机推荐
【LeetCode】226.翻转二叉树
箭头函数与普通函数的区别
Mysql的in和exists用法区别
36氪详情页AES
sqlite date field plus one day
PowerShell:执行 Install-Module 时,不能从 URI 下载
Scala parallel collections, parallel concurrency, thread safety issues, ThreadLocal
Redisson实现分布式锁
Path Prefixes (倍增!树上の二分)
内存模型之有序性
用diskpart的offline命令弹出顽固硬盘
Docker starts mysql
牛客 - 最佳直播时间 (差分)
dflow入门1——HelloWorld!
AI mid-stage sequence labeling task: three data set construction process records
数仓4.0(一)
"Swordsman Offer" brush questions print from 1 to the largest n digits
ceph简介
进程信息
110 MySQL interview questions and answers (continuous updates)









