# flatmap

* [集合的 flatmap操作](https://www.selinux.tech/scala/function-operation/pages/-Lriuq0R2Ra67BN0aGpN#集合的-flatmap操作)
  * [函数的定义](https://www.selinux.tech/scala/function-operation/pages/-Lriuq0R2Ra67BN0aGpN#函数的定义)
  * [作用](https://www.selinux.tech/scala/function-operation/pages/-Lriuq0R2Ra67BN0aGpN#作用)

## 函数的定义

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

首先以 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
  }

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.selinux.tech/scala/function-operation/flatmap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
