object collection_t1 { def flatMap1(): Unit = { val li = List(1,2,3) val res = li.flatMap(x => x match { case 3 => List(‘a‘,‘b‘) case _ => List(x*2) }) println(res) } def map1(): Unit = { val li = List(1,2,3) val res = li.map(x => x match { case 3 => List(‘a‘,‘b‘) case _ => x*2 }) println(res) } def main(args: Array[String]): Unit = { flatMap1() map1() } }
result: List(2, 4, a, b) List(2, 4, List(a, b))
flatMap就是在Map的基础上加了压平flatten的功能
foldLeft 从左边起折叠,累加
https://alvinalexander.com/scala/scala-reduceleft-examples
讲解reduceleft
时间: 2024-10-28 06:38:46