jdk1.8中方法引用
时间: 2023-10-24 11:16:41 浏览: 56
方法引用是 JDK 1.8 中的一个新特性,它允许我们通过方法的名称来引用已经存在的方法,从而替代 Lambda 表达式。方法引用的语法格式为:
```
object :: methodName
```
其中,`object` 可以是类名、对象名或者是一个表达式,`methodName` 则是一个方法名。
方法引用可以分为 4 种类型:
1. 静态方法引用:引用静态方法。
```
类名::methodName
```
2. 实例方法引用:引用某个对象的实例方法。
```
对象名::methodName
```
3. 特定类的任意对象的实例方法引用:引用特定类的任意对象的实例方法。
```
类名::methodName
```
4. 构造方法引用:引用构造方法。
```
类名::new
```
下面是一些示例:
1. 静态方法引用:
```java
// Lambda 表达式
Function<String, Integer> toInteger = s -> Integer.parseInt(s);
// 方法引用
Function<String, Integer> toInteger = Integer::parseInt;
```
2. 实例方法引用:
```java
// Lambda 表达式
BiPredicate<List<Integer>, Integer> contains = (list, element) -> list.contains(element);
// 方法引用
BiPredicate<List<Integer>, Integer> contains = List::contains;
```
3. 特定类的任意对象的实例方法引用:
```java
// Lambda 表达式
BiFunction<String, String, Boolean> startsWith = (s1, s2) -> s1.startsWith(s2);
// 方法引用
BiFunction<String, String, Boolean> startsWith = String::startsWith;
```
4. 构造方法引用:
```java
// Lambda 表达式
Supplier<List<String>> listSupplier = () -> new ArrayList<>();
// 方法引用
Supplier<List<String>> listSupplier = ArrayList::new;
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)