1.java8中引入了一个新的操作符:“->”,左侧->右侧
左侧:lambda表达式的参数列表(函数式接口的形参列表)
右侧:lambda表达式的中执行的的功能,即lambda体(函数式接口的具体实现)
2.举例
Car1.java
1/**
2 * 函数式接口(无参,无返回值)
3 * @author gnehcgnaw
4 * @date 2018/10/19 11:11
5 */
6@FunctionalInterface
7public interface Car1 {
8 public void printColor();
9}
Car2.java
1/**
2 * 函数式接口(有参,有返回值)
3 * @author gnehcgnaw
4 * @date 2018/10/19 11:11
5 */
6@FunctionalInterface
7public interface Car2 {
8 /**
9 * 有参,有返回值
10 * @param x
11 * @return
12 */
13 public int getWheelCount(int x);
14}
TestLambda.java
1import lombok.extern.slf4j.Slf4j;
2import org.junit.Test;
3/**
4 * @author gnehcgnaw
5 * @date 2018/10/19 11:12
6 */
7@Slf4j
8public class TestLambda1 {
9 @Test
10 public void test(){
11 //无参,无返回值
12 Car1 car1 = ()->System.out.print(1);
13 car1.printColor();
14 }
15 @Test
16 public void test2(){
17 //有参,有返回值
18 //int conut = getConut(3, (x -> x+1));
19 int conut = getConut(3, (x) -> {
20 return x + 1;
21 });
22 log.info("{}",conut);
23 }
24 public int getConut(int x ,Car2 car2){
25 return car2.getWheelCount(x) ;
26 }
27}
3.lambda有一个前提就是:函数式接口,函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。例子:用注解@FunctionalInterface校验是否满足函数式接口,下列程序没有报错说明了函数式接口的定义确实可以有非抽象方法的存在,但是只能有一个抽象方法。
1/**
2 * 测试函数式接口的定义
3 * @author gnehcgnaw
4 * @date 2018/10/19 11:11
5 */
6@FunctionalInterface
7public interface Car2 {
8 /**
9 * 有参,有返回值
10 * @param
11 * @return
12 */
13 default int getq(){
14 return 1 ;
15 }
16 static String printColour(){
17 return "red" ;
18 }
19 public int getWheelCount(int x);
20}
4.在使用lambda的时候真的每次都要自定义一个函数式接口吗?其实是不用的,在Java1.8及其以后的版本都提供了juf的包(java.util.function)很多的函数式接口供我们选择使用。有的地方有四大内置函数式接口,这里就不再累述,其实就是juf中的顶层接口而已。

文章转载自程序猿wangc,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




