当前位置:网站首页>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)
}
}
边栏推荐
猜你喜欢
随机推荐
【论文笔记】一种基于启发式奖赏函数的分层强化学习方法
Redis集群概念与搭建
scala 并行集合、并行并发、线程安全问题、ThreadLocal
ArcEngine (2) loading the map document
HCIP练习(OSPF)
dflow入门1——HelloWorld!
Redis的基础与django使用redis
FusionAccess软件架构、FusionAccess必须配置的四个组件、桌面发放流程、虚拟机组类型、桌面组类型
AI中台序列标注任务:三个数据集构造过程记录
箭头函数与普通函数的区别
redis stream 实现消息队列
LAN技术-2免费ARP
Eject stubborn hard drives with diskpart's offline command
scala reduce、reduceLeft 、reduceRight 、fold、foldLeft 、foldRight
Pop Harmony Basics Big Notes
线程介绍与使用
dflow入门3——dpdispatcher插件
数据监控平台
Docker starts mysql
PowerShell:执行 Install-Module 时,不能从 URI 下载









