一、lambda表达式中的方法引用是什么?
四大函数式接口
Consumer : 消费型接口
- void accept(T t);
Supplier : 供给型接口
- T get();
Function : 函数型接口
- R apply(T t);
Predicate : 断言型接口
- boolean test(T t);
1、方法引用:lambda体中的内容已经有方法实现了,我们可以使用方法引用的形式
2、方法引用的三种形式
(1)对象::实例方法名
(2)类::静态方法名
(3)类::实例方法名
二、使用步骤
1.对象::实例方法名
函数式接口中的方法的参数列表和返回值类型必须与方法名保持一致
例:
void accept(T t)
public void println(int x)
Consumer consumer = System.out::println;
consumer.accept(2);
代码如下(示例):
Consumer<Integer> consumer = System.out::println;
consumer.accept(2);
2.类::静态方法名
代码如下(示例):
//public static int compare(int x, int y) compare是Integer的静态方法
Comparator<Integer> comparator = Integer::compare;
int compare = comparator.compare(1, 2);
3.类::实例方法名
lambda表达式中第一参数是实例方法的调用者,第二参数是实例方法的参数时,可以使用ClassName::method
代码如下(示例):
//public boolean equals(Object anObject)
//boolean test(T t, U u);
BiPredicate<String, String> predicate1 = String::equals;
boolean test = predicate1.test("s", "s");