waitwolf 2020-07-08
在Scala中可以通过map映射操作来解决:
将集合中的每一个元素通过指定功能(函数)映射(转换)成新的结果集合这里其实就是所谓的将函数作为参数传递给另外一个函数,这是函数式编程的特点
以HashSet为例说明
def map[B](f: (A) ⇒ B): HashSet[B] //map函数的签名
1)这个就是map映射函数集合类型都有
2)[B] 是泛型
3)map 是一个高阶函数(可以接受一个函数的函数,就是高阶函数),可以接收 函数 f: (A) => B 后面详解(先简单介绍下.)
4) HashSet[B] 就是返回的新的集合
def main(args: Array[String]): Unit = {
val list1 = List(3, 5, 7)
def f1(n1: Int): Int = {
println("xxx")
2 * n1
}
val list2 = list1.map(f1)
println(list2)
val myList = MyList()
val myList2 = myList.map(f1)
println("myList2=" + myList2)
println("myList=" + myList.list1)
}class MyList {
var list1 = List(3, 5, 7)
var list2 = List[Int]()
def map(f:Int=>Int): List[Int] = {
for (item<-list1) {
list2 = list2 :+ f(item)
}
list2
}
}
object MyList {
def apply(): MyList = new MyList()
}flatmap:flat即压扁,压平,扁平化,效果就是将集合中的每个元素的子元素映射到某个函数并返回新的集合。
看一个案例:
val names = List("Alice", "Bob", "Nick")
def upper( s : String ) : String = {
s. toUpperCase
}
//注意:每个字符串也是char集合
println(names.flatMap(upper))