Lambda是Java 8引入的新特性,在Java语法层面,Lambda表达式允许函数作为一个方法的参数(函数作为参数传递到方法中);在具体实现上主要依靠了JVM底层提供的 Lambda相关API (现有语法的封装 )
注:部分代码示例和说明是转载使用
Lambda表达式
- 语法:
(参数列表)箭头操作符 Lambda体
( (int) arg1, (String) arg2) -> {..}- 参数类型可选; int, String 可省
- 参数列表只含有一个参数可省略( );
- Lambda体如果只含有一个语句,则可省略{ },类似于实现了函数式接口中的方法。
注:Lambda表达式可简化函数式接口的使用,常与内部类对比使用,函数式接口即有且仅有一个抽象方法的接口;函数式接口可以显示地被@FunctionallInterface 所表示。
- Application:简化接口使用
public class TestLambda {
public static void main(String[ ] args) {
// regular invocation
ICar car1 =new ICarImpl();
car1.drive();
// Anonymous class
ICar car2 =new ICar() { public void drive() { System.out.println("Drive BenzX3"); }
car2.drive();
// Lambda
ICar car3 = ( )-> System.out.println("Drive BenzQ7");
car3.drive();
IDriver car4 =(who)->{ System.out.println(who+" is driving");};
car4.drive("Eli");
ICleaner car5 = (fare, month) -> fare*month; // (fare,month)->{return fare*month};
System.out.println("Benz cleaning costs: "+car5.wash(3.8,5));
}
}
interface ICa { void drive( ); }
interface IDriver { void drive ( String driver ); }
interface ICleaner { double wash ( final double fare, int month ); }
class ICarImpl implements ICar{
public void drive( ) {
System.out.println("Drive Benz");
}
}
- 3 Application:
public static void main(String[] args) {
ArrayList arr =new ArrayList( );
arr.add("Eli");
arr.add("Josh");
arr.add("Mike");
arr.forEach( n -> System.out.println(n) );
}
方法引用 --- 更简约的Lambda表达式
- 方法引用是Java 8 引入的新特性,可以直接引用已有的Java类或对象的方法或构造器,相比于Lambda表达式,可以简化代码。
- Lambda表达式可被方法引用代替:Lambda表达式的主体仅包含一个表达式,且该表达式仅调用了一个已经存在的方法。方法引用的通用特性:方法引用中所使用方法的参数列表和返回值与lambda表达式实现的函数式接口的参数列表和返回值一致。
public static void main(String[] args) {
ArrayList arr =new ArrayList();
arr.add("Eli");
arr.add("Josh");
arr.add("Mike");
// arr.forEach(n-> System.out.println(n));
arr.forEach(System.out::println);
// 若arr.forEach( n -> System.out.println(n+1) ); 则不能使用方法引用替换
}
方法引用类型:
注:Function,Consumer,Predicate,Supplier等为Java 8 内置的函数式接口
类型1:方法引用
Class name :: Static Method
Class name :: Instance Method
Instance object :: Instance Method
/**
* 类名::静态方法
*/
// Comparator com = (x,y)-> Integer.compare(x,y);
Comparator com = Integer::compare;
/**
* 类名:: 实例方法
*/
// Predicate bp = (x,y) -> x.equals(y);
Predicate bp = String::equals;
/**
* 对象:: 实例方法
*/
// Consumer con = x-> System.out.println(x);
PrintStream out = System.out;
Consumer con = out::println;
类型2:构造器引用
Class name :: new
Class name[ ] :: new
/**
* 类:: new
*/
//Supplier supplier = () -> new String();
Supplier supplier = String::new;
类型3:数组引用
Type :: new
/**
* 数组类型:: new
*/
//Function fun = x -> new String[x];
Function fun = String[]::new;