Lambda表达式使用强化
lambda表达式是jdk1.8新加入的特效,目的是简化代码书写,可用于函数式接口
函数式接口就是该接口只有一个实现方法,有多个方法的不能称之为函数式接口
我把lambda的使用分成以下几类,简单来说lambda表达式就是()->{}
1.函数式接口无参无返回值
public static void test1(){
//函数式接口可以这样写,函数式接口就是接口只有一个方法需要实现,这个时候可以用lambda表达式简化写法
//()就是无参的意思,->后{}内容就是实现方法,实现方法是无参
TestInterface testInterface = ()->{
System.out.println("你好");
};
testInterface.sayHello();
//如果重写的函数只有一行,那连{}都可以省略
TestInterface testInterface1 = ()-> System.out.println("你好");;
}
public interface TestInterface {
public void sayHello();
}
2.函数式接口有一个参数无返回值
public static void test2(){
//同样实现方法是无返回值,但是有一个String参数,可以下面这么写
TestInterface2 testInterface = (String str)-> System.out.println(str);
testInterface.sayHello("你好");
//java会类型推断,所以String str可以直接写成str,而且当参数只有一个的时候,()都可以省略
TestInterface2 testInterface1 = str -> System.out.println(str);
}
public interface TestInterface2 {
public void sayHello(String str);
}
3.函数式接口有两个参数无返回值
public static void test3(){
//这个函数式接口的实现方法需要两个参数,一个是String,一个是int。用lambda表达式时java会自己推断类型,所以无需写成String str这样的形式
//由于方法有两个参数,所以()不能省略,因为执行语句不止一条,所以{}不能省略
TestInterface3 testInterface = (str,num)->{
System.out.println(str);
System.out.println(num);
System.out.println(str+num);
};
testInterface.sayHello("你好",10);
}
public interface TestInterface3 {
public void sayHello(String str,Integer num);
}
4.函数式接口有2个参数且有返回值
public static void test4(){
//由于这个接口的实现方法有类型返回,所以需要写return
TestInterface4 testInterface = (str,num)->{
return str+num;
};
//如果实现方法只有单条return语句,那么连return都可以返回,同样,单条语句可以不写{}
TestInterface4 testInterface1 = (str, num) ->str+num;
}
public interface TestInterface4 {
public String sayHello(String str,Integer num);
}
5.函数式接口有返回值且参数也是一个接口
public static void test5(){
//如果接口需要调用别的接口
TestInterface5 testInterface = testInterface1 -> testInterface1.sayHello("str",10);
String s = testInterface.sayHello((str, num) ->str+num);
System.out.println(s+"----------");
}
public interface TestInterface5 {
public String sayHello(TestInterface4 testInterface);
}