一、在JDK8以前,Java是不支持函数式编程的java
二、认识Lambda表达式编程
传统方法:ide
new Thread(new Runnable() { @Override public void run() { System.out.println("Hello World!"); } });
Lambda表达式一句话就够了:函数式编程
new Thread(() -> System.out.println("Hello World!"));
三、举例:函数
/** * 函数接口:只有一个方法的接口。做为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类库接口
以前代码:get
for (Student student : studentList) { if (student.getCity().equals("chengdu")) { count++; } }
JDK8使用集合的正确姿式:
count = studentList.stream().filter((student -> student.getCity().equals("chengdu"))).count();