Lambda表达式

Lambda表达式是一个匿名函数,可以理解为一段可以传递的代码(将代码像数据一样进行传递)

Lambda表达式的使用

语法

  • ->Lambda操作符或者箭头操作符
  • ->左边Lambda形参列表(接口中抽象方法的形参列表)
  • ->右边Lambda体(重写抽象方法的方法体)
  • Lambda表达式本质上是接口的一个实例

Lambda表达式使用六种场景实例

场景一:无参、无返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class LambdaTest {
public static void main(String[] args) {
//创建线程实例
Runnable r1 = new Runnable(){
@Override
public void run() {
System.out.println("We are Family");
}
};
r1.run();
//使用Lambada表达式进行改写
Runnable r2 = () -> System.out.println("We are family Lambda");
r2.run();
}
}

场景二:Lambda表达式需要一个参数,但是没有返回值

1
2
3
4
5
6
7
8
9
10
11
public class LambdaTest2 {
@Test
public void test1(){
//lambda表达式有参无返回值
MyInterface myInterface = (String str) -> System.out.println(str);
myInterface.func("张飞");
}
}
interface MyInterface{
void func(String str);
}

场景三:数据类型可以省略,因为可由编译器推断得出,称之为类型推断

1
2
3
4
5
6
7
8
9
10
public class LambdaTest2 {
@Test
public void test1(){
MyInterface<String> myInterface = (str) -> System.out.println(str);
myInterface.func("张飞");
}
}
interface MyInterface<T>{
void func(T str);
}

场景四:Lambda表达式若只需要一个参数,参数的小括号可以省略

1
2
3
4
5
6
7
8
9
10
public class LambdaTest2 {
@Test
public void test1(){
MyInterface<String> myInterface = str -> System.out.println(str);
myInterface.func("张飞");
}
}
interface MyInterface<T>{
void func(T str);
}

场景五:Lambda表达式需要两个或者以上的参数,多条执行语句,并且可以有返回值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class LambdaTest2 {
@Test
public void test1(){
MyInterface myInterface = (String s1,String s2,int i) -> {
String s = s1+s2+i;
return s;
};
String res = myInterface.func("李白","张飞",22);
System.out.println(res);
}
}
interface MyInterface{
String func(String str1,String str2,int num);
}

场景六:当Lambda体只有一条语句时,return与大括号都可以省略

1
2
3
4
5
6
7
8
9
10
11
public class LambdaTest2 {
@Test
public void test1(){
MyInterface myInterface = (String s1,String s2,int i) -> s1+s2+i;
String res = myInterface.func("李白","张飞",22);
System.out.println(res);
}
}
interface MyInterface{
String func(String str1,String str2,int num);
}