版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/oXinYangonly/article/details/81427723
Lambda表达式基本语法
java8中引入了一个新的操作符 ->
,它将lambda
表达式,拆分成了参数列表和表达式所需执行的功能(Lambda体)两部分
其实所谓的Lambda
表达式,实际上就是对接口的实现,表达式的参数列表就是接口中抽象方法的参数列表,Lambda
体就是抽象方法的实现
- 无参数、无返回值
new Thread(()->{
System.out.println("Hello");
}).start();
如果lambda体中之后一行代码,则可以省略大括号
new Thread(()-> System.out.println("Hello")).start();
- 一个参数,无返回值
Consumer<String> consumer = (x)-> System.out.println(x);
consumer.accept("有参数无返回值");
- 只有一个参数,则可以省略小括号
Consumer<String> consumer = x-> System.out.println(x);
- 有多个参数,并且
Lambda
体中有多条语句
Comparator<Integer> com = (x,y)->{
System.out.println("多个参数,有返回值");
return Integer.compare(x,y);
};
- 有多个参数,
Lambda
体中只有一条语句,return
和大括号都可以省略
Comparator<Integer> com = (x,y)->Integer.compare(x,y);
Lambda
表达式的参数列表的数据类型可以省略,JVM编译器会通过上线文推断出数据类型,即类型推断
Lambda表达式需要函数式接口的支持
- 函数式接口
接口中只有一个抽象方法的几口,称为函数式接口。可以使用@FunctionalInterface
修饰,可以检查是否是函数式接口
内置函数式接口
- 消费型接口
Consumer<T> void accept(T t)
- 供给型接口
Supplier<T> T get()
- 函数型接口
Function<T,R> R apply(T t)
- 断言型接口
Predicate<T> boolean test(T t)
方法引用
如果Lambda表达式中的内容已经存在实现的方法,就可以使用方法引用
方法引用的三种语法格式
- 对象::对象方法名
PrintStream ps = System.out;
Consumer<String> consumer = ps::println;
或者可以直接写为
Consumer<String> consumer = System.out::println;
- 类::静态方法名
Comparator<Integer> comparator = Integer::compare;
- 类::对象方法名
BiPredicate<String,String> biPredicate = (x,y)->x.equals(y);
可以写为
BiPredicate<String,String> biPredicate = String::equals;
1.
Lambda
表达式中,调用方法的参数列表与返回值类型要与函数式接口中抽象方法的参数列表和返回值类型保持一致
2.lambda表达中有两个参数,如果第一个参数是对象方法的调用者,第二个方法是调用方法的参数,就可以使用类::对象方法
的方式
构造方法引用
ClassName::new
Supplier<String> supplierStr = ()->new String();
可以写为
Supplier<String> supplierStr = String::new;
需要调用的构造方法的参数列表要与函数式接口中抽象方法的参数列表保持一致
数组引用
Function<Integer,String[]> fun = (x) = new String[x];
可以写为
Function<Integer,String[]> fun = String[]::new;