Lambda表达式

Lambda表达式

作为JDK8的新特性,Lambda表达式提供了更方便的写法(匿名内部类)

Lambda表达式的本质,是一个对象,也是一个匿名函数


Lambda表达式的使用举例

(o1, o2) -> Integer.compare(o1,o2);


Lambda表达式的格式说明

-> :Lambda操作符或箭头操作符

->的左边:Lambda形参列表,对应着重写方法的形参列表

->的右边:Lambda体,对应着重写方法的方法体


类型推断*

1
2
3
4
5
6
7
8
9
@Test
public void test(){
//类型推断
int[] arr1 = new int[]{1, 2, 3, 4};
int[] arr2 = {1,2,3,4};
//类型推断
HashMap<String, Integer> stringIntegerHashMap1 = new HashMap<String,Integer>();
HashMap<String, Integer> stringIntegerHashMap = new HashMap<>();
}

类型推断的功能导致了->左边的形参可以省略声明类型


Lambda实例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Test
public void test2() {
//使用匿名内部类重写compare方法完成对两个数的对比
Comparator<Integer> com1 = new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
};
System.out.println(com1.compare(23, 21));

//Lambda表达式的写法
Comparator<Integer> com2 = (o1, o2) -> Integer.compare(o1,o2); //类型推断,形参没有写明数据类型
System.out.println(com2.compare(23, 21));
//方法引用
Comparator<Integer> com3 = Integer :: compare;
System.out.println(com3.compare(23,21));
}

当->左边的形参列表只有一个参数时,甚至可以省掉形参列表中的小括号

当->右边的执行体只有一条语句时,大括号可以省略,如有return语句,return关键字必须省略


函数式接口

如果接口中只有一个抽象方法,则此接口就成为函数式接口**@FunctionalInterface**

函数式接口所在的包:声明在java.util.function包下

四个基本的函数式接口

函数式接口 称谓 参数类型 用途
Consumer <T> 消费型接口 T 包含方法:void accept(T t) 有参无返回值
Supplier<T> 供给型接口 包含方法:T get() 有返回值无参数
Function<T,R> 函数式接口 T 包含方法:R apply(T t) 有形参有返回值
Predicate<T> 判断型接口 T 包含方法:boolean test(T t) 有形参有布尔类型返回值

Lambda表达式
http://blog.170827.xyz/2024/03/23/Lambda表达式/
作者
XIAOBAI
发布于
2024年3月23日
许可协议