java8-lambda(2)语法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/answer100answer/article/details/87894972

上一篇文章:java8-lambda(1)

1.语法格式

  • 无参,无返回值 格式()->...
    Runnable为例
	@Test
    public void test1(){
        //原始实现
        Runnable r1 = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello");
                System.out.println("old");
            }
        };
        r1.run();
        
        //lambda实现
        Runnable r2 = ()-> System.out.println("lambda");//可以{}中写多条
        r2.run();
    }
  • 一个参数,无返回值 格式(arg)->...或省略小括号arg->...
    Consumer接口为例,该接口中有无返回值的accept方法:
	//2.一个参数无返回值
    @Test
    public void test2(){
        Consumer con = (x) -> System.out.println(x+"测试consumer");
        con.accept("111"); //111测试consumer
    }
  • 多参有返回值 格式 (arg1,arg2)->{...; ...}
    当lambda体中只有一条语句时,return和大括号都可以省略
    Comparator为例:
    //3.多参数
    @Test
    public void test3(){
        // return和{}
        Comparator<Integer> com = (x,y)->{return Integer.compare(x,y);};
        // 省略return和{}
        Comparator<Integer> com1 = (x,y)->Integer.compare(x,y);
        Comparator<Integer> com2 = (x,y)->(x-y);
    }
  • 类型推断可以省略数据类型
       Comparator<Integer> c = (Integer x,Integer y)->(x-y);
       //如类型推断
       String[] strs={"a","b"};

2.lambda表达式需要函数式接口的支持

函数式接口概念:

  • 只包含一个抽象方法的接口,称为函数式接口
  • 你可以通过 Lambda 表达式来创建该接口的对象。(若 Lambda表达式抛出一个受检异常,那么该异常需要在目标接口的抽象方法上进行声明)。
  • 我们可以在任意函数式接口上使用 @FunctionalInterface 注解,
    这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包 含一条声明,说明这个接口是一个函数式接口。

自定义函数接口示例
这种接口往往作为其他方法的参数再次被调用。

1.定义接口

@FunctionalInterface
public interface MyFun<T> {
    T getValue(T t);
}

2.定义使用接口函数

    /**
     * 函数式接口编程
     */
    public Integer operator(Integer num, MyFun<Integer> fun){
        return fun.getValue(num);
    }

3.使用该函数并用lambda实现接口

    @Test
    public void test4(){
        int res = operator(200, x->x+1);
        System.out.println(res); //201
    }

上一篇:java8-1.lambda
下一篇: java8-3.内置的函数接口

猜你喜欢

转载自blog.csdn.net/answer100answer/article/details/87894972
今日推荐