lambda表达式需要一个函数式接口(有且仅有一个抽象方法,但是可以有多个非抽象方法的接口,可以使用 @FunctionalInterface 修饰)
语法格式1:无参数,无返回值 接口举例:Runnable接口
Runnable r = new Runnable{
@Override
public void run(){
System.out.println("Hello World");
}
}
r.run();
Runnable r = ()->System.out.println("Hello World");
r.run();
语法格式2:有一个参数,无返回值 接口举例:Consumer
Consumer<String> con = (x)->System.out.println();
con.accept();
语法格式3:有多个参数,有返回值 接口举例:Comparator
// lambda体中有多条语句
Comparator<Integer> com = (x, y)->{
System.out.println("Hello world");
return Integer.compare(x,y);
}
// lambda 体中只有一条语句, return和大括号可以不写
Compator<Integer> com = (x, y) -> Integer.compare(x, y);
Java8 内置的四大核心函数式接口
Consumer<T>
void accept(T t);
Supplier<T>
T get();
Function<T, R>
R apply(T t);
Predicate<T>
boolean test(T t);
以Function为例
public void test(){
String newStr = strHandler("\t\t\t abc ", (str) -> str.trim());
String newStr = strHandler("abcde", (str) -> str.substring(2, 5));
}
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}