reduce()——规约操作,包含reduceLeft()和reduceRight()两种操作。
fold()——折叠操作,包含foldLeft()和foldRight()两种操作。
两者功能相似,不同之处在于:
fold()操作需要从一个初始值开始,并以该值作为上下文,处理集合中的每个元素。
reduce()操作举例:
-
scala> val list = List(1,2,3,4,5)
-
list: List[Int] = List(1, 2, 3, 4, 5)
-
-
scala> list.reduceLeft((x:Int,y:Int)=>{println(x,y);x+y})
-
(1,2)
-
(3,3)
-
(6,4)
-
(10,5)
-
res0: Int = 15
-
-
scala> list.reduceRight((x:Int,y:Int)=>{println(x,y);x+y})
-
(4,5)
-
(3,9)
-
(2,12)
-
(1,14)
-
res1: Int = 15
-
scala> val list = List(1,2,3,4,5)
-
list: List[Int] = List(1, 2, 3, 4, 5)
-
-
scala> list.reduceLeft((x:Int,y:Int)=>{println(x,y);x-y})
-
(1,2)
-
(-1,3)
-
(-4,4)
-
(-8,5)
-
res2: Int = -13
-
-
scala> list.reduceRight((x:Int,y:Int)=>{println(x,y);x-y})
-
(4,5)
-
(3,-1)
-
(2,4)
-
(1,-2)
-
res3: Int = 3
fold()操作举例:
-
scala> val list = List(1,2,4,3,5)
-
list: List[Int] = List(1, 2, 4, 3, 5)
-
-
scala> list.fold(10)(_*_)
-
res0: Int = 1200
-
scala> list.foldLeft(0)((x:Int,y:Int)=>{println(x,y);x+y})
-
(0,1)
-
(1,2)
-
(3,4)
-
(7,3)
-
(10,5)
-
res1: Int = 15
-
-
scala> list.foldRight(0)((x:Int,y:Int)=>{println(x,y);x+y})
-
(5,0)
-
(3,5)
-
(4,8)
-
(2,12)
-
(1,14)
-
res2: Int = 3
上面fold(10)(_*_),fold(0)中,10和0就是进行fold()操作所附的初值。