Java8学习笔记(一)--Lambda表达式

两个概念

函数式接口

函数式接口就是只显式声明一个抽象方法的接口。为保证方法数量不多不少,java8提供了一个专用注解@FunctionalInterface,这样,当接口中声明的抽象方法多于或少于一个时就会报错。如下图所示:

Lambda表达式

Lambda表达式本质上是一个匿名方法。让我们来看下面这个例子:

public int add(int x, int y) {
    return x + y;
}

转成Lambda表达式后是这个样子:

(int x, int y) -> x + y;

参数类型也可以省略,Java编译器会根据上下文推断出来:

(x, y) -> x + y; //返回两数之和

或者

(x, y) -> { return x + y; } //显式指明返回值

可见Lambda表达式有三部分组成:参数列表,箭头(->),以及一个表达式或语句块。

Lambda表达式和函数式接口结合

步骤:

  1. 新建无参函数式接口(先演示无参);
  2. 新建包含属性为函数式接口的类;
  3. 实现函数式接口;
  4. 测试函数式接口的方法;

新建无参函数式接口

@FunctionalInterface
public interface InterfaceWithNoParam {
    void run();
}

新建包含属性为函数式接口的类

public class TestJava8{
InterfaceWithNoParam param;
}

实现函数式接口

public class TestJava8{
	//匿名内部类
	InterfaceWithNoParam param1 = new InterfaceWithNoParam() {
        @Override
        public void run() {
            System.out.println("通过匿名内部类实现run()");
        }
    };
	//Lambda表达式
            //空括号表示无参
	InterfaceWithNoParam param = () -> System.out.println("通过Lambda表达式实现run()") ;
}

测试函数式接口的方法

@Test
public void testIntfaceWithNoparam() {

    this.param.run();
    this.param1.run();
}

运行结果

其他形式的函数式接口及实现

上述内容实现了无参无返回值的函数接口与实现,当然还有其他形式:

  1. 有参无返回值
  2. 无参有返回值
  3. 有参有返回值

有参无返回值

接口

@FunctionalInterface
public interface InterfaceWithParams {
    void run(String s);
}

实现

InterfaceWithParams params = new InterfaceWithParams() {
    @Override
    public void run(String s) {
        System.out.println("通过" + s + "实现run(String)");
    }
};
InterfaceWithParams params1 = (String s) -> System.out.println("通过" + s + "实现run(String)");

测试

    this.params.run("匿名类");
    this.params1.run("Lambda");

运行

无参有返回值

接口

@FunctionalInterface
public interface InterfaceUnVoidWithNoParam {
    String run();
}

实现

InterfaceUnVoidWithNoParam interfaceUnVoidWithNoParam = new InterfaceUnVoidWithNoParam() {
    @Override
    public String run() {
        return "Hello World!";
    }
};
InterfaceUnVoidWithNoParam interfaceUnVoidWithNoParam1 = () -> "Hello Lambda!";

测试

    String s = this.interfaceUnVoidWithNoParam.run();
    System.out.println("返回结果是:"+s);
    String s0 = this.interfaceUnVoidWithNoParam1.run();
    System.out.println("返回结果是:"+s0);

运行

有参有返回值

接口

@FunctionalInterface
public interface InterfaceUnVoidWithParams {
    String run(Integer integer);
}

实现

InterfaceUnVoidWithParams interfaceWithParams = new InterfaceUnVoidWithParams() {
    @Override
    public String run(Integer integer) {
        return String.valueOf(integer);
    }
};
InterfaceUnVoidWithParams interfaceWithParams1 = (Integer integer) -> String.valueOf(integer);

测试

    String s1 = this.interfaceWithParams.run(1);
    System.out.println("您输入的是:"+s1);
    String s2 = this.interfaceWithParams1.run(2);
    System.out.println("您输入的是:"+s2);

运行

posted @ 2017-08-08 00:35  舒山  阅读(16927)  评论(3编辑  收藏  举报