foldLeft 练习题

 

 

//     将2个集合中相同的元素求和
    val map1 = scala.collection.mutable.Map('a' -> 1, 'b' -> 2, 'c' -> 3)
    val map2 = scala.collection.mutable.Map('a' -> 1, 'b' -> 2, 'c' -> 3)

      val tuples: List[(Char, Int)] = map1.foldLeft(map2)((map, t) => {
          map(t._1) = map.getOrElse(t._1, 0) + t._2
          map
      }).toList.sortWith((v1, v2) => v1._2 < v2._2)
      println(tuples)

 

 

 

 

posted @ 2022-10-25 22:06  linbo.yang  阅读(15)  评论(0编辑  收藏  举报