object MapOperateDemo1 {
def main(args: Array[String]): Unit = {
val list1 = List(1, 2, 3)
var list2 = List[Int]()
for (item <- list1) {
list2 = list2 :+ item * 2
}
println("list2:" + list2)
}
}
上面的Demo有几个问题:
不够简洁、高效
没有函数式编程
不利于处理复杂的数据处理业务
由此我们引出下面的map映射操作。
集合元素map映射操作
将集合中的每一个元素通过指定功能(函数) 映射(转换)成新的结果集。
以 Seq 为例,可以看到它的map方法定义。
def map[B](f: (A) ⇒ B): Seq[B]
[use case]
Builds a new collection by applying a function to all elements of this sequence.
B the element type of the returned collection.
f the function to apply to each element.
returns a new sequence resulting from applying the given function f to each element of this sequence and collecting the results.
Demo2 函数式实现
object MapOperateDemo2 {
def main(args: Array[String]): Unit = {
val list = List(1, 2, 3)
val list2 = list.map(multiple)
println(list2)
// 简化写法
val list3 = list.map(_ * 2)
println(list3)
val list4 = list.map(n => n * 2)
println(list4)
}
def multiple(n: Int): Int = {
println("被调用") //调用三次
n * 2
}
}
将list中的元素全部遍历出来
将遍历出来的元素传递给multiple
将得到的值,放入到一个新的集合并返回
Demo3 编程实现map操作
object MapOperateDemo2 {
def main(args: Array[String]): Unit = {
// 模拟 map 的实现机制
val myList1 = DemoList()
val myList2 = myList1.map(_ * 2)
println(myList2)
}
}
class DemoList {
val list1 = List(1, 4, 5, 6)
var list2 = List[Int]()
def map(f: Int => Int): List[Int] = {
// 遍历这个集合
for (elem <- list1) {
list2 = list2 :+ f(elem)
}
list2
}
}
object DemoList {
def apply(): DemoList = new DemoList()
}