Java 8 lambda表达式

1、在JDK8之前,Java是不支持函数式编程的

  • 函数编程,即可理解是将一个函数(也称为“行为”)作为一个参数进行传递
  • 面向对象编程是对数据的抽象(各种各样的POJO类)
  • 函数式编程则是对行为的抽象(将行为作为一个参数进行传递)

2、认识Lambda表达式

传统方法:

  • 带来许多不必要的“样板代码”
new Thread(new Runnable() {
    @Override
    public void run() {
        System.out.println("Hello World!");
    }
});

Lambda表达式一句话就够了:

new Thread(() -> System.out.println("Hello World!"));

3、举例:

  • 只要是一个接口中只包含一个方法,则可以使用Lambda表达式,这样的接口称之为“函数接口”
/**
 * 函数接口:只有一个方法的接口。作为Lambda表达式的类型
 * Created by Kevin on 2018/2/17.
 */
public interface FunctionInterface {
    void test();
}

/**
 * 函数接口测试
 * Created by Kevin on 2018/2/17.
 */
public class FunctionInterfaceTest {

    @Test
    public void testLambda() {
        func(new FunctionInterface() {
            @Override
            public void test() {
                System.out.println("Hello World!");
            }
        });
        //使用Lambda表达式代替上面的匿名内部类
        func(() -> System.out.println("Hello World"));
    }

    private void func(FunctionInterface functionInterface) {
        functionInterface.test();
    }
}

4、包含参数

  • 参数类型可以不指明(建议任何情况下都指明)
/**
 * 函数接口测试
 * Created by Kevin on 2018/2/17.
 */
public class FunctionInterfaceTest {

    @Test
    public void testLambda() {
        //使用Lambda表达式代替匿名内部类
        func((x) -> System.out.println("Hello World" + x));
    }

    private void func(FunctionInterface functionInterface) {
        int x = 1;
        functionInterface.test(x);
    }
}

5、函数接口是一个泛型,不能推导出参数类型

/**
 * 函数接口:只有一个方法的接口。作为Lambda表达式的类型
 * Created by Kevin on 2018/2/17.
 */
public interface FunctionInterface<T> {
    void test(T param);
}

6、带参数带返回值

func((Integer x) -> {
    System.out.println("Hello World" + x);
    return true;
});

7、Lambda 表达式,更大的好处则是集合API的更新,新增的Stream类库

  • 遍历使用集合时不再像以往那样不断地使用for循环

之前代码:

for (Student student : studentList) {
    if (student.getCity().equals("chengdu")) {
        count++;
    }
}

JDK8使用集合的正确姿势:

count = studentList.stream().filter((student -> student.getCity().equals("chengdu"))).count();

猜你喜欢

转载自my.oschina.net/u/3847203/blog/1825673