# Java基础——方法引用

方法引用（Method Reference）是对 lambda 表达式的一种转换表达，也称双冒号运算。

## 语法格式

```java
className:: methodName
或
objectName:: methodName
```

## Demo

```java
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
```

采用 forEach 方法遍历上述 list

```java
list.forEach(new Consumer<Integer>() {
    @Override
    public void accept(Integer i) {
        System.out.println(i);
    }
});
```

由于 Consumer 接口是函数式接口，可以使用 lambda 改写

```java
list.forEach(i -> System.out.println(i));
```

继续采用 Method Reference 改写

```java
list.forEach(System.out:: println);
```


---

# 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://lewiszlw.gitbook.io/notebooks/blogs/history/java-ji-chu-fang-fa-yin-yong.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.
