Lambda表达式的语法
基本语法:
(parameters) -> expression
或
(parameters) ->{ statements; }
复制代码
方法引用
方法引用分为三种,方法引用通过一对双冒号:: 来表示,方法引用是一种函数式接口的另一种书写方式
- 静态方法引用,通过类名::静态方法名, 如 Integer::parseInt
- 实例方法引用,通过实例对象::实例方法,如 str::substring
- 也可以类名::实例方法名, 如 String::substring
- 构造方法引用,通过类名::new, 如 User::new
第三点: 若Lambda 的参数列表的第一个参数,是实例方法的调用者,第二个参数(或无参)是实例方法的参数时,格式: 类名::实例方法名
There are several basic function shapes,
including Function (unary function from T to R), Consumer (unary function from T to void), Predicate (unary function from T to boolean), and Supplier (nullary function to R).
Function shapes have a natural arity based on how they are most commonly used. The basic shapes can be modified by an arity prefix to indicate a different arity, such as BiFunction (binary function from T and U to R).
类名::方法名,相当于对这个方法闭包的引用,类似js中的一个function。比如:
public static void main(String[] args) {
Consumer<String> printStrConsumer = DoubleColon::printStr;
printStrConsumer.accept("printStrConsumer");
Consumer<DoubleColon> toUpperConsumer = DoubleColon::toUpper;
toUpperConsumer.accept(new DoubleColon());
BiConsumer<DoubleColon,String> toLowerConsumer = DoubleColon::toLower;
toLowerConsumer.accept(new DoubleColon(),"toLowerConsumer");
BiFunction<DoubleColon,Stri