当前位置:网站首页>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)
}
}
边栏推荐
猜你喜欢
随机推荐
Alibaba Cloud SMS Sending
ArcEngine (2) loading the map document
审批流设计
ArcEngine (six) use the tool tool to realize the zoom in, zoom out and translation of the pull box
响应式布局经典范例——巨幅背景大标题
The Transformer, BERT, GPT paper intensive reading notes
牛客 - 鼠标的天选(字符串哈希)
Redis集群概念与搭建
国内IT市场还有发展吗?有哪些创新好用的IT运维工具可以推荐?
dflow入门3——dpdispatcher插件
用diskpart的offline命令弹出顽固硬盘
C# 一周入门高级编程之《C#-继承》Day One
WPS EXCEL 筛选指定长度的文本 内容 字符串
10分钟带你入门chrome(谷歌)浏览器插件开发
【LeetCode】226.翻转二叉树
Guava-字符串工具
HCIA实验(07)
积分商城系统设计
手把手教你如何自制目标检测框架(从理论到实现)
gpnmb+ gpnmb-AT2 cell空转映射 上皮细胞的空转映射









