# filter

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

## 函数的定义

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

```scala
def filter(p: (A) ⇒ Boolean): Seq[A]
  Selects all elements of this traversable collection which satisfy a predicate.

  p
  the predicate used to test elements.

  returns
  a new traversable collection consisting of all elements of this traversable collection that satisfy the given predicate p. The order of the elements is preserved.
```

## 作用

将集合中符合条件的 元素 筛选出来，放入到一个新的集合中，并返回这个新的集合。 这些操作，对原来的集合是没有影响的。

```scala
object FilterDemo1 {

  def main(args: Array[String]): Unit = {
    val list = List("Tom", "Aerry", "Jack").filter(startA)

    println(list)

  }

  def startA(string: String):Boolean ={
    string.startsWith("A")
  }

}
```

```scala
object FilterDemo2 {

  def main(args: Array[String]): Unit = {
    val list = List("Tom", "Aerry", "Jack").filter(_.startsWith("A"))

    println(list)
  }

}
```


---

# 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/filter.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.
