> For the complete documentation index, see [llms.txt](https://www.selinux.tech/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.selinux.tech/scala/function-operation/flatmap.md).

# flatmap

* [集合的 flatmap操作](https://www.selinux.tech/pages/-Lriuq0R2Ra67BN0aGpN#%E9%9B%86%E5%90%88%E7%9A%84-flatmap%E6%93%8D%E4%BD%9C)
  * [函数的定义](https://www.selinux.tech/pages/-Lriuq0R2Ra67BN0aGpN#%E5%87%BD%E6%95%B0%E7%9A%84%E5%AE%9A%E4%B9%89)
  * [作用](https://www.selinux.tech/pages/-Lriuq0R2Ra67BN0aGpN#%E4%BD%9C%E7%94%A8)

## 函数的定义

将 二元函数 引用于集合中的函数

首先以 Seq 的flatmap函数定义来进行理解。

```scala
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.
```

## 作用

将集合中每个**元素的子元素**映射(**转换**)到某个函数并返回新的集合。

```scala
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
  }

}
```
