fold
- Combine the external elements of the collection and the internal elements of the collection
fold
- The bottom layer is called foldLeft, which folds from left to right.
- It is required that the parameter types outside the two collections and the parameter types in the collection must be consistent .
val list1: List[Int] = List(3, 5, 9, 10, 11)
println(list1.fold(6)(_ - _))
foldLeft
- Fold from left to right.
- The parameter types outside the collection can be different from the parameter types in the collection .
println(list1.foldLeft(6)(_ + _))
foldRight
- Fold from right to left.
- The parameter types outside the collection can be different from the parameter types in the collection .
- foldRight is the reverse set, and then foldLeft is called.
println(list1.foldRight(6)(_ - _))
Case study
- Combine the elements in the two Map collections.
analysis
- Two different sets are used to fold.
- One of the parameters is a tuple and the other is a map type, so use foldLeft|foldRight.
achieve
val map1: mutable.Map[String, Int] = mutable.Map("a" -> 1, "b" -> 2, "c" -> 3)
val map2: mutable.Map[String, Int] = mutable.Map("a" -> 2, "b" -> 3, "d" -> 4)
val res = map1.foldLeft(map2) {
(m2, kv) => {
val k: String = kv._1
val v: Int = kv._2
m2(k) = m2.getOrElse(k, 0) + v
m2
}
}
val res2: mutable.Map[String, Int] = map2.foldLeft(map1) {
(m1, kv) => {
val k: String = kv._1
val v: Int = kv._2
m1(k) = m1.getOrElse(k, 0) + v
m1
}
}
println(res2)