前言
我們知道JDK8是一個比較大版本的更新,其給我們帶來了很多新特性,其中有一個非常重要的知識點叫做lambda表達(dá)式。
Lambda表達(dá)式的介紹
官方解釋:Lambda表達(dá)式是Java8中最重要的新功能之一。使用Lambda表達(dá)式可以替代只有一個抽象函數(shù)的接口實現(xiàn),告別匿名內(nèi)部類,代碼看起來更簡潔易懂。Lambda表達(dá)式同時還提升了對集合、框架的迭代、遍歷、過濾數(shù)據(jù)的操作。
官方文檔地址:https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.27
案例1、使用Thread(Runnable runnable)創(chuàng)建一個線程
@Test
public void testCreateThread() {
// JDK8之前的寫法
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("running1......");
}
}).start();
// 使用Lambda表達(dá)式的形式
new Thread(() -> {System.out.println("running2......");}).start();
}
案例2、對集合內(nèi)的元素進(jìn)行排序
public void testSortList() {
// 定義一個集合
List<String> list = Arrays.asList("java", "C", "python", "scala");
// JDL8之前的寫法
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
for (String s : list) {
System.out.println(s);
}
System.out.println("==========================");
// Lambda表達(dá)式的寫法 如果{}中只有一行代碼的話 {;}可以省略 o1, o2的參數(shù)類型自動推斷
Collections.sort(list, (o1, o2) -> o1.length() - o2.length());
list.forEach(System.out::println);
}
為什么使用Lambda表達(dá)式
我們先來看一個案例
public class WhyUseLambda1 {
@Test
public void testWhyUseLambda() {
List<Student> list = new ArrayList<>();
list.add(new Student("張三", 13, 63));
list.add(new Student("李四", 18, 78));
list.add(new Student("王五", 14, 70));
list.add(new Student("小紅帽", 16, 89));
list.add(new Student("小綠", 19, 69));
// 需求1: 查找年齡大于16的學(xué)生
findByAge(list);
System.out.println("=======================");
// 需求2: 查找分?jǐn)?shù)大于75的學(xué)生
findByScore(list);
}
// 查找年齡大于16的學(xué)生: 不使用Lambda的寫法
private void findByAge(List<Student> list) {
List<Student> students = new ArrayList<>();
for (Student student : list) {
if (student.getAge().intValue() > 16) {
students.add(student);
}
}
for (Student student : students) {
System.out.println(student);
}
}
// 查找分?jǐn)?shù)大于75的學(xué)生: 不使用Lambda的寫法
private void findByScore(List<Student> list) {
List<Student> students = new ArrayList<>();
for (Student student : list) {
if (student.getScore().intValue() > 75) {
students.add(student);
}
}
for (Student student : students) {
System.out.println(student);
}
}
}
上面的代碼還是比較簡單的,但是出現(xiàn)代碼重復(fù)的現(xiàn)象,現(xiàn)在我們對其進(jìn)行優(yōu)化
public interface StudentFilter {
public boolean match(Student student);
}
public class StudentAgeFilter implements StudentFilter {
@Override
public boolean match(Student student) {
return student.getAge() > 16;
}
}
public class StudentScoreFilter implements StudentFilter {
@Override
public boolean match(Student student) {
return student.getScore() > 75;
}
}
public class WhyUseLambda2 {
@Test
public void testWhyUseLambda() {
List<Student> list = new ArrayList<>();
list.add(new Student("張三", 13, 63));
list.add(new Student("李四", 18, 78));
list.add(new Student("王五", 14, 70));
list.add(new Student("小紅帽", 16, 89));
list.add(new Student("小綠", 19, 69));
// 需求1: 查找年齡大于16的學(xué)生
findByFilter(list, new StudentAgeFilter());
System.out.println("=======================");
// 需求2: 查找分?jǐn)?shù)大于75的學(xué)生
findByFilter(list, new StudentScoreFilter());
}
private void findByFilter(List<Student> list, StudentFilter filter) {
List<Student> students = new ArrayList<>();
for (Student student : list) {
if (filter.match(student)) {
students.add(student);
}
}
printStudent(students);
}
private void printStudent(List<Student> list) {
for (Student student : list) {
System.out.println(student);
}
}
}
通過這個案例的代碼看起來已經(jīng)沒有重復(fù)的代碼了,但是還是存在一個問題,比如我現(xiàn)在想以名字的長度來過濾的話,就需要再寫一個Filter類,這時我們看到這個StudentFilter接口的實現(xiàn)類只被使用一次,因此我們首先想到的就是直接使用匿名內(nèi)部類就行了
public class WhyUseLambda3 {
@Test
public void testWhyUseLambda() {
List<Student> list = new ArrayList<>();
list.add(new Student("張三", 13, 63));
list.add(new Student("李四", 18, 78));
list.add(new Student("王五", 14, 70));
list.add(new Student("小紅帽", 16, 89));
list.add(new Student("小綠", 19, 69));
// 需求1: 查找年齡大于16的學(xué)生
findByFilter(list, new StudentFilter() {
@Override
public boolean match(Student student) {
return student.getAge() > 16;
}
});
System.out.println("=======================");
// 需求2: 查找分?jǐn)?shù)大于75的學(xué)生
findByFilter(list, new StudentFilter() {
@Override
public boolean match(Student student) {
return student.getScore() > 75;
}
});
System.out.println("=======================");
// 需求3: 查找名字的長度大于2的學(xué)生
findByFilter(list, new StudentFilter() {
@Override
public boolean match(Student student) {
return student.getName().length() > 2;
}
});
}
private void findByFilter(List<Student> list, StudentFilter filter) {
List<Student> students = new ArrayList<>();
for (Student student : list) {
if (filter.match(student)) {
students.add(student);
}
}
printStudent(students);
}
private void printStudent(List<Student> list) {
for (Student student : list) {
System.out.println(student);
}
}
}
到此我們再思考一下這些代碼又臭又長的,能不能優(yōu)化一下呢?這時我們今天的主角就可以登場了。
public class WhyUseLambda4 {
@Test
public void testWhyUseLambda() {
List<Student> list = new ArrayList<>();
list.add(new Student("張三", 13, 63));
list.add(new Student("李四", 18, 78));
list.add(new Student("王五", 14, 70));
list.add(new Student("小紅帽", 16, 89));
list.add(new Student("小綠", 19, 69));
// 需求1: 查找年齡大于16的學(xué)生
findByFilter(list, (student) -> student.getAge() > 16);
System.out.println("=======================");
// 需求2: 查找分?jǐn)?shù)大于75的學(xué)生
findByFilter(list, (student)-> student.getScore() > 75);
System.out.println("=======================");
// 需求3: 查找名字的長度大于2的學(xué)生
findByFilter(list, (student) -> student.getName().length() > 2);
}
private void findByFilter(List<Student> list, StudentFilter filter) {
List<Student> students = new ArrayList<>();
for (Student student : list) {
if (filter.match(student)) {
students.add(student);
}
}
printStudent(students);
}
private void printStudent(List<Student> list) {
for (Student student : list) {
System.out.println(student);
}
}
}
Lambda表達(dá)式的特點
函數(shù)式編程
參數(shù)類型自動推斷
代碼量少,簡潔
Lambda表達(dá)式的應(yīng)用場景
任何有函數(shù)式接口的地方
Lambda表達(dá)式的寫法
Lambda表達(dá)式的格式
LambdaParameters -> LambdaBody
表達(dá)式說明
args -> expr 獲取(Object ... args) -> {函數(shù)式接口抽象方法實現(xiàn)邏輯}
()參數(shù)個數(shù),根據(jù)函數(shù)式接口里面抽象的參數(shù)個數(shù)來決定,當(dāng)參數(shù)只有一個的時候()可以省略。
當(dāng)expr邏輯非常簡單,只有一行代碼的時候,{}和return可以省略。
-> :Lambda Operator(Lambda操作符)
表達(dá)式案例
() -> {}
() -> {System.out.println(1);}
() -> System.out.println(1)
() -> {return 100;}
() -> 100
() -> null
(int x) -> {return x+1;}
(int x) -> x+1
(x) -> x+1
x -> x+1
@Test
public void testUseLambda() throws Exception {
Runnable runnable1 = new Runnable() {
@Override
public void run() {
System.out.println("runnable1...");
}
};
runnable1.run();
Runnable runnable2 = () -> {
System.out.println("runnable2...");
};
runnable2.run();
Runnable runnable3 = () -> System.out.println("runnable3...");
runnable3.run();
System.out.println("========================================");
Callable<String> callable1 = new Callable<String>() {
@Override
public String call() throws Exception {
return "callable1...";
}
};
System.out.println(callable1.call());
Callable<String> callable2 = () -> {
return "callable2...";
};
System.out.println(callable2.call());
Callable<String> callable3 = () -> "callable3...";
System.out.println(callable3.call());
System.out.println("========================================");
Function<Integer, String> function1 = new Function<Integer, String>() {
@Override
public String apply(Integer integer) {
return "function" + integer;
}
};
System.out.println(function1.apply(1));
Function<Integer, String> function2 = (Integer integer) -> {
return "function" + integer;
};
System.out.println(function2.apply(2));
Function<Integer, String> function3 = (integer) -> {
return "function" + integer;
};
System.out.println(function3.apply(3));
Function<Integer, String> function4 = (integer) -> {
return "function" + integer;
};
System.out.println(function4.apply(4));
Function<Integer, String> function5 = integer -> {
return "function" + integer;
};
System.out.println(function5.apply(5));
Function<Integer, String> function6 = integer -> "function" + integer;
System.out.println(function6.apply(6));
}
JDK中定義的函數(shù)式接口
Supplier:代表一個輸出
Consumer:代表一個輸入
BiConsumer:代表兩個輸入
Function:代表一個輸入,一個輸出(一般輸入和輸出是不同類型的)
UnaryOperator:代表一個輸入,一個輸出(輸入和輸出是相同類型的)
BiFunction:代表兩個輸入,一個輸出(一般輸入和輸出是不同類型的)
BinaryOperator:代表兩個輸入,一個輸出(輸入和輸出是相同類型的)
Lambda表達(dá)式的使用
函數(shù)式接口
我們知道C語言是面向過程編程,Java是面向?qū)ο缶幊蹋酥庀馪ython、Scala語言等它們幾乎都是函數(shù)式編程的一種語言。
在java里面方法是不能作為我們的形式參數(shù)的,java里面要求方法參數(shù)傳遞必須是值傳遞。但是在某些方法里面可以將函數(shù)作為參數(shù)傳遞進(jìn)去,這種方式就叫做函數(shù)式編程。
函數(shù)式接口的定義
只有一個抽象方法(Object類中的方法除外)的接口叫做函數(shù)式接口。
示例:
@FunctionalInterface
public interface InterfaceTest {
public void add();
//public void sub();
}
在這里有一個@FunctionInterface注解,如果你將public void sub()方法的注釋放開的話,這個注釋就會報錯。
Lambda表達(dá)式的原理
方法的引用
方法引用的定義
方法引用是用來直接訪問類或者實例的已經(jīng)存在的方法或者構(gòu)造方法,方法引用提供了一種引用而不執(zhí)行方法的方式,如果抽象方法的實現(xiàn)恰好可以使用調(diào)用另外一個方法來實現(xiàn),就有可能可以使用方法的引用。
方法引用也屬于Lambda表達(dá)式。
方法引用的分類
| 類型 | 語法 | 對應(yīng)的Lambda表達(dá)式 |
|---|---|---|
| 靜態(tài)方法引用 | 類名::staticMethod | (args) -> 類名.staticMethod(args) |
| 實例方法引用 | inst::instMethod | (args) -> inst.instMethod(args) |
| 對象方法引用 | 類名::instMethod | (inst,args) -> 類名.instMethod(inst,args) |
| 構(gòu)造方法引用 | 類名::new | (args) -> new 類名(args) |
靜態(tài)方法引用:如果函數(shù)式接口的實現(xiàn)恰好可以通過調(diào)用一個靜態(tài)方法來實現(xiàn),那么就可以使用靜態(tài)方法引用。
實例方法引用:如果函數(shù)式接口的實現(xiàn)恰好可以通過調(diào)用一個實例的方法來實現(xiàn),那么就可以使用實例方法引用。
對象方法引用:抽象方法的第一個參數(shù)類型剛好是實例方法的類型,抽象方法剩余的參數(shù)恰好可以當(dāng)作實例方法的參數(shù)。如果函數(shù)式接口的實例能由上面說的實例方法調(diào)用來實現(xiàn)的話,那么就可以使用對象方法引用。
構(gòu)造方法引用:如果函數(shù)式接口的實現(xiàn)恰好可以通過調(diào)用一個類的構(gòu)造方法來實現(xiàn),那么就可以使用構(gòu)造方法引用。
案例演示
public class MethodRefTest {
/**
* 靜態(tài)方法引用:如果函數(shù)式接口的實現(xiàn)恰好可以通過調(diào)用一個靜態(tài)方法來實現(xiàn),那么就可以使用靜態(tài)方法引用。
*/
@Test
public void testStaticMethodRef() {
Supplier<String> supplier = Foo::staticMethod;
System.out.println(supplier.get());
}
/**
* 實例方法引用:如果函數(shù)式接口的實現(xiàn)恰好可以通過調(diào)用一個實例方法來實現(xiàn),那么就可以使用實例方法引用。
*/
@Test
public void testInstanceMethodRef() {
Foo foo = new Foo();
Supplier<String> supplier = foo::instanceMethod;
System.out.println(supplier.get());
}
/**
* 對象方法引用案例演示
* 抽象方法的第一個參數(shù)類型,剛好是實例方法的類型, 抽象方法的參數(shù)恰好可以當(dāng)中實例方法的參數(shù)
* 如果函數(shù)式接口的實例能由上面說的實例方法調(diào)用來實現(xiàn)的話, 那么就可以使用對象方法引用
*/
@Test
public void testObjMethodRef() {
Foo foo1 = new Foo();
System.out.println(foo1);
Consumer<Foo> consumer1 = (foo) -> {new Foo().foo();};
consumer1.accept(foo1);
Consumer<Foo> consumer3 = Foo::foo;
consumer3.accept(foo1);
Consumer<Foo> consumer2 = (foo) -> {new Foo2().foo();};
//Consumer<Foo> consumer4 = Foo2::foo;
}
/**
* 構(gòu)造方法引用: 如果函數(shù)式接口的實現(xiàn)恰好可以通過調(diào)用一個類的構(gòu)造方法來實現(xiàn),那么就可以使用構(gòu)造方法引用
*/
@Test
public void testConstructMethodRef() {
Supplier<Foo2> s1 = () -> new Foo2();
Supplier<Foo2> s2 = Foo2::new;
s1.get();
s2.get();
Consumer<String> c = Integer::new;
}
private static class Foo {
public static String staticMethod() {
return "function reference1";
}
public String instanceMethod() {
return "function reference2";
}
public void foo() {
System.out.println("foo:" + this);
}
}
private class Foo2 {
public void foo() {
System.out.println("foo");
}
}
}