Java 8 lambda表达式

一、在JDK8以前,Java是不支持函数式编程的java

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

二、认识Lambda表达式编程

传统方法:ide

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

Lambda表达式一句话就够了:函数式编程

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

三、举例:函数

  • 只要是一个接口中只包含一个方法,则能够使用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();
    }
}

四、包含参数测试

  • 参数类型能够不指明(建议任何状况下都指明)
/**
 * 函数接口测试
 * 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);
    }
}

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

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

六、带参数带返回值对象

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

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

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

以前代码:get

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

JDK8使用集合的正确姿式:

count = studentList.stream().filter((student -> student.getCity().equals("chengdu"))).count();
相关文章
相关标签/搜索