java8-新特性-lambda

java8-新特性-lambda

前言

  • 理解 : 可以把Lambda表达式理解为简洁的表示可传递的匿名函数的一种方式:

    • 它没有名称,但它有参数列表,函数主体,返回类型,可能还有一个可以抛出的异常列表。
  • java中,引入了一个新的操作符“->”,该操作符在很多资料中,称为箭头操作符,或者lambda操作符;箭头操作符将lambda分成了两个部分:

    1. 左侧:lambda表达式的参数列表
    2. 右侧:lambda表达式中所需要执行的功能,即lambda函数体
    3. lambda表达式语法格式;
  • 函数式接口定义:接口中只有一个抽象方法的接口,称为函数式接口;

    • 可以使用@FunctionalInterface注解修饰,对该接口做检查;如果接口里,有多个抽象方法,使用该注解,会有语法错误

1. 无参数

  • 无参数,无返回值的用法 :() -> System.out.println(“hello lambda”);
1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void test1() {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("hello runnable");
}
};
r.run();
Runnable r1 = () -> System.out.println("hello lambda");
r1.run();
}

2. 有一个参数,无返回值

  • 有一个参数,无返回值的用法:(x) -> System.out.println(x);或者x -> System.out.println(x);一个参数,可以省略参数的小括号
1
2
3
4
5
@Test
public void test2(){
Consumer<String> con = (x) -> System.out.println(x);
con.accept("有一个参数,无返回值的用法(Consumer函数式接口)");
}

3. 有两个参数,有返回值

1
2
3
4
public void test3() {
BinaryOperator<Integer> binary = (x, y) -> x + y;
System.out.println(binary.apply(1, 2));// 3
}

4. 小结使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@Test
public void test4() {
// 无返回值lambda函数体中用法
Runnable r1 = () -> {
System.out.println("hello lambda1");
System.out.println("hello lambda2");
System.out.println("hello lambda3");
};
r1.run();

// 有返回值lambda函数体中用法
BinaryOperator<Integer> binary = (x, y) -> {
int a = x * 2;
int b = y + 2;
return a + b;
};
System.out.println(binary.apply(1, 2));// 6

}
  • 可以看到,多行的,只需要用大括号{}把语句包含起来就可以了;
  • 有返回值和无返回值的,只有一个return的区别;
  • 只有一条语句的,大括号和return都可以不用写;

5. 参数类型

1
2
3
4
5
@Test
public void test5() {
BinaryOperator<Integer> binary = (Integer x, Integer y) -> x + y;
System.out.println(binary.apply(1, 2));// 3
}
  • 可以看到,在lambda中的参数列表,可以不用写参数的类型,跟java7中 new ArrayList<>(); 不需要指定泛型类型,这样的<>棱形操作符一样,根据上下文做类型的推断
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信