一、在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();