Lambda 表达式(二)

本贴最后更新于 820 天前,其中的信息可能已经东海扬尘

3、 函数式接口

问:Lambda表达式的类型是什么?

答:函数式接口

问:函数式接口是什么?

答:只包含一个抽象方法的接口,称为函数式接口 (functional interface) , 一般用@FunctionalInterface注解来检测是否是函数式接口。

3.1、自定义函数式接口

@FunctionalInterface
public interface MyFunctionalInterface {
    String test(String p);
}

使用泛型
@FunctionalInterface
public interface MyFunctionalInterface<T,R> {
    R test(T t);
}

3.2、函数式接口作为方法参数

public void test(MyFunctionalInterface mfi,String str) {
    System.out.println(mfi.getValue(str));
}

调用test()
test(p -> p.toUpperCase(),"luojie");
控制台输出
LUOJIE

3.2、常见函数式接口

函数式接口名称 参数类型 返回值 方法
Consumer T void void accept(T t)
Supplier T T get();
Function<T,R> T R R apply(T t);
Predicate T boolean boolean test(T t);
BiFunction<T,U,R> T,U R R apply(T t, U u);
UnaryOperator T T T apply(T t);
BinaryOperator T,T T T apply(T t1, T t2);
BiConsumer<T,U> T,U void void accept(T t, U u)

4、方法引用

问:什么是方法引用?

答:当我们需要完成的Lambda体操作,已经有实现的方法了,可以使用方法引用!

问:为什么用方法引用?

答:省略参数,少写代码

4.1、举个例子

Comparator<Integer> com2 = (x, y) -> Integer.compare(x,y);
//上面我们之前学过的Lambda表达式,其中Lambda体操作是比较两个整数的大小,
//而且Integer的compare()正好完就是我需要完成的操作。
//可以方法引用替代
Comparator<Integer> com3 = Integer::compare;

4.2、方法引用格式

方法引用使用操作符 :: 将方法名和对象或类的名字分开。
分三种格式:

4.2.1、类::静态方法

(x, y) -> Integer.compare(x,y);
方法引用改造:
Integer::compare;

4.2.2、对象::实例方法

(x) -> System.out.printf(x);
方法引用改造
System.out::println;

4.2.2、类::实例方法

test((x,y)->x.equals(y),"123","123");
方法引用改造
test(String::equals,"123","abc");  
注意当引用方法的第一个参数是调用对象并且第二个参数是需要传入参数(或无参数)ClassName::methodName
比如上例子中"123"当作equals方法调用对象,"abc"为传入equals()参数
相当于"123".equals("abc")
回帖
请输入回帖内容 ...