刚学习JAVA的小伙伴不建议看。
首先你先要明白这段代码是作什么的?
Comp<Integer> com = new Comp<Integer>{
public int compare(Integer a1,Integer a2){
return Integer.compare(a1,a2);
}
};
然后你要知道这两段代码所表达的是同一东西。
Comp<Integer> com = (x,y)-> Integer.compare(x,y);
Lambda表达式的基础语法:
Java8中引入了一个“->”操作符,该操作符别成为Lambda操作符吗,他将Lambda表达式拆分为两部分:
左边:Lambda表达式的参数列表。
右边:Lambda表达式中所需执行的功能,即为Lambda体。
语法格式一:无参数,无返回值
()->System.out.println("")
语法格式二:有一个参数,无返回值
(X)-> System.out.print("xx")
语法格式三:若只有一参数参数,小括号可以省略不写
x->System.out.println("sss")
语法格式四:有两个以上的参数,有返回值,并且Lambda体中有多条语句
(x,y)->{
System.out.println("xx");
return x+y;
}
语法格式五:若Lambda体中只有一条语句,return和大括号都可以省略不写
(x,y)->Integer.compare(x,y)
语法格式六:Lambda表达式的参数列表的数据类型都可以省略不写,因为JVM编译器可以通过上下文推断出来,即“类型推断”。
(Integer x, Integer y)->Integer.compare(x,y);
Lambda表达式需要“函数式接口”的支持
函数式接口:接口中只有一个抽象方法的接口,称为函数接口。
Java8内置四大核心的函数接口
Consumer<T>:消费型接口 void accept(T t);
Supplier<T>:供给型 T get(T t);
Function<T,R>:函数型接口 R apply(T t);
Predicate<T>:断言型接口 boolean test(T t);
例:
用内置函数
public class test{
@Test
public void test1(){
apply(1,(a)-> System.out.println(a))
}
public void apply(Inetger a,Consumer<Integer> con){
con.acccpet(a);
}
}
//没有用到内置函数
public class test1{
public static void main(String args[]){
test1 tes = new test1();
tes.operate(10, 5, (int a, int b) -> a + b)
}
interface Operation {
int operation1(int a, int b);
}
private int apply(int a, int b, Operation operation){
return operation.operation1(a, b);
}
}
可以看出用内置函数比不用内置函数省区了定义接口这部分的代码。
以上是我总结Lambda表达式知识。希望大佬们可以补充。谢谢