def flatMap[B](f: (A) ⇒ GenTraversableOnce[B]): Seq[B]
[use case]
Builds a new collection by applying a function to all elements of this sequence and using the elements of the resulting collections.
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 collection-valued function f to each element of this sequence and concatenating the results.
作用
将集合中每个元素的子元素映射(转换)到某个函数并返回新的集合。
object FlatMapDemo01 {
def main(args: Array[String]): Unit = {
// 对所有元素进行扁平化
val list = List("Tom", "Jerry", "Jack")
val list2 = list.flatMap(upper)
println(list2)
}
def upper(string: String):String={
string.toUpperCase
}
}