前提:必须要一个接口式函数(接口中只有一个抽象方法)的支持,
可以使用注解@FunctionalInterface(用这个注解修饰的接口必须是函数是接口,作用和@override差不多),
lambda表达式的基础语法: jajava8引入了一个新的操作符:“->”,该操作符简称为箭头操作符或者lambda操作符
箭头操作符拆分为两部分:
左侧:lambda表达式的参数列表(对应的是接口中方法的参数列表)
右侧:lambda表达式所执行的功能:lambda体(对应的是接口中方法的实现)
语法表达式: 1.无参数,无返回值: ()->System.out.println("");
2.有参数(如果有且只有一个参数,小括号可以省略),无返回值:(e)->System.out.println(e);或者e ->System.out.println(e);
3.有多个参数,有返回值,lambda体中有多条语句:
Comparator<Integer> comparator = (x,y) ->{
System.out.println("函数式接口");
return Integer.compare(x, y);
};
4.有多个参数,有返回值,lambda体中只有一条语句:
return 和大括号可以省略
Comparator<Integer> comparator = (x,y) ->Integer.compare(x, y);
5,lambda表达式的参数列表的参数类型可以省略不写,因为jvm编辑器可以通过上下文推断出数据类型,即类型推断
左右遇一括号省
左侧推断类型省
能省则省
java内置的四大核心函数是接口对象(有了这些接口就不用自己去定义一个接口了) Consumer<T>(消费性接口) void accept(T t);
Supper<T> 供给型接口
T get();
Function<T,R> 函数型接口
R apply(T t);
Predicate<T> 断言型接口
boolean test(T t); 这些接口下还有一些子接口,可以根据自己的需要调用
方法引用:若lambda中的内容有方法已经实现了,我们可以方法引用(lambda方法的另一种表现形式) 主要有三种形式:注意lambda体中调用方法的参数列表与返回值类型,要与函数是接口的方法得参数列表与返回值保持一致
1.对象::实例方法名
2.类::静态方法名
3.类::实例方法名
若lambda参数列表中的第一个参数是方法的调用者,第二个参数是方法的参数时,可以使用类名::方法名 [java] view plain copy
- public void test() {
- PrintStream pStream = System.out;
- Consumer<String> consumer = x->pStream.println(x);
- PrintStream ps = System.out;
- Consumer<String> consumer1 = ps::print;
- Consumer<String> consumer2 = System.out::println;
- consumer2.accept("gagag");
- }
- //对象::实例方法名
- public void test1() {
- Employee employee = new Employee();
- Supplier<String> supplier = ()->employee.getName();
- String string = supplier.get();
- System.out.println(string);
- Supplier<Integer> supplier2 = employee::getAge;
- Integer integer = supplier2.get();
- System.out.println(integer);
-
- }
- //.类::静态方法名
- public void test2() {
- Comparator<Integer> comparator = (x,y)->Integer.compare(x, y);
- //同上
- Comparator<Integer> comparator2 = Integer::compare;
- }
- //类::实例方法名
- public void test3() {
- BiPredicate<String, String> bp = (x,y)->x.equals(y);
- BiPredicate<String, String> bp1 = String::equals;
- }
【转载】原文地址:https://blog.csdn.net/object_oriented/article/details/80722301
|