1. Lambda表達式
1.1 Lambda使用場景
Lambda表達式是java8引入的新特性,直接點說,就是新的一種java語法,是每一個java程序猿必須掌握的技能。它的使用場景是,當我需要實現一個被@FunctionalInterface註解修飾的接口時,我們就可以使用Lambda表達式。比如我們需要一個實現了Runnable接口的類,或需要一個實現了Comparator接口的類,再或者我們自定義了一個接口(接口被@FunctionalInterface註解),當我們需要這個接口的實現類的時候,也可以直接使用lambda表達式。
@FunctionalInterface註解的作用是,告訴jvm,這個接口是隻包含一個方法的接口。所以,我們編寫的lambda表達式就是對這個接口僅有的一個方法的實現!只要被這個註解修飾的接口,我們就稱它爲函數式接口。從目前的經驗看,lambda表達式實現這個接口方法的時候,是無法像一個正常的接口實現類那樣還能新增實現類的屬性,或者新增其他方法等。如果想讓實現類具備自己的屬性,或者定義其他方法,那還是按照原來的寫法,去實現這個接口吧。
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
使用Lambda創建一個Runnable的實現類,來執行一個線程,代碼如下
public void test1(){
//jdk 1.7 前,必須是 final
int num = 0;
// 使用匿名內部類的方式
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Hello World!" + num);
}
};
r.run();
System.out.println("分割線-------------------------------");
// 使用lambda 一行代碼實現Runnable接口的run方法
Runnable r1 = () -> System.out.println("Hello Lambda!");
r1.run();
}
1.2 Lambda基礎語法
Lambda 表達式的基礎語法:Java8中引入了一個新的操作符 "->" 該操作符稱爲箭頭操作符或 Lambda 操作符:箭頭操作符將 Lambda 表達式拆分成兩部分:
左側:Lambda 表達式的參數列表
右側:Lambda 表達式中所需執行的功能, 即 Lambda 體
- 語法格式一:實現的接口方法無參數,無返回值
Runnable r1 = () -> System.out.println("Hello Lambda!");
- 語法格式二:實現的接口方法有一個參數,並且無返回值
(x) -> System.out.println(x); //x是隨便起的名字,想叫什麼都行
- 語法格式三:實現的接口方法若只有一個參數,小括號可以省略不寫
x -> System.out.println(x)
- 語法格式四:實現的接口方法有兩個以上的參數,有返回值,並且 Lambda 體中有多條語句
Comparator<Integer> com = (x, y) -> {
System.out.println("函數式接口");
return Integer.compare(x, y);
};
// lambda表達式需要多條語句,那就用{},有返回值則最後使用return
- 語法格式五:若 Lambda 體中只有一條語句, return 和 大括號都可以省略不寫
Comparator<Integer> com = (x, y) -> Integer.compare(x, y);
- 語法格式六:Lambda 表達式的參數列表的數據類型可以省略不寫,因爲JVM編譯器通過上下文推斷出,數據類型,即“類型推斷”
(Integer x, Integer y) -> Integer.compare(x, y);
通過上面的語法總結,只要我們需要一個函數式接口的實現類的簡單實現時,就可以直接使用lambda表達式,來表示這個實現類。
1.3 Java8 內置的四大核心函數式接口
通過上面的學習,我們知道寫lambda之前必須先有一個函數式接口,那麼java8就爲我們提供了四大核心函數式接口。
- Consumer<T> : 消費型接口 void accept(T t);
- Supplier<T> : 供給型接口 T get();
- Function<T, R> : 函數型接口 R apply(T t);
- Predicate<T> : 斷言型接口 boolean test(T t);
package com.wqh.demo.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.junit.Test;
/*
* Java8 內置的四大核心函數式接口
*
* Consumer<T> : 消費型接口
* void accept(T t);
*
* Supplier<T> : 供給型接口
* T get();
*
* Function<T, R> : 函數型接口
* R apply(T t);
*
* Predicate<T> : 斷言型接口
* boolean test(T t);
*
*/
public class TestLambda3 {
//Predicate<T> 斷言型接口:
@Test
public void test4(){
List<String> list = Arrays.asList("Hello", "atguigu", "Lambda", "www", "ok");
List<String> strList = filterStr(list, (s) -> s.length() > 3);
for (String str : strList) {
System.out.println(str);
}
}
//需求:將滿足條件的字符串,放入集合中
public List<String> filterStr(List<String> list, Predicate<String> pre){
List<String> strList = new ArrayList<>();
for (String str : list) {
if(pre.test(str)){
strList.add(str);
}
}
return strList;
}
//Function<T, R> 函數型接口:
@Test
public void test3(){
String newStr = strHandler("\t\t\t 我大中華威武 ", (str) -> str.trim());
System.out.println(newStr);
String subStr = strHandler("我大中華威武", (str) -> str.substring(2, 5));
System.out.println(subStr);
}
//需求:用於處理字符串
public String strHandler(String str, Function<String, String> fun){
return fun.apply(str);
}
//Supplier<T> 供給型接口 :
@Test
public void test2(){
List<Integer> numList = getNumList(10, () -> (int)(Math.random() * 100));
for (Integer num : numList) {
System.out.println(num);
}
}
//需求:產生指定個數的整數,並放入集合中
public List<Integer> getNumList(int num, Supplier<Integer> sup){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
Integer n = sup.get();
list.add(n);
}
return list;
}
//Consumer<T> 消費型接口 :
@Test
public void test1(){
happy(10000, (m) -> System.out.println("你們剛哥喜歡大寶劍,每次消費:" + m + "元"));
}
public void happy(double money, Consumer<Double> con){
con.accept(money);
}
}
1.4 Lambda方法引用
一、方法引用:若 Lambda 體中的功能,已經有方法提供了實現,可以使用方法引用(可以將方法引用理解爲 Lambda 表達式的另外一種表現形式)
1. 對象的引用 :: 實例方法名
2. 類名 :: 靜態方法名
3. 類名 :: 實例方法名
注意:
①方法引用所引用的方法的參數列表與返回值類型,需要與函數式接口中抽象方法的參數列表和返回值類型保持一致!
②若Lambda 的參數列表的第一個參數,是實例方法的調用者,第二個參數(或無參)是實例方法的參數時,格式: ClassName::MethodName
//對象的引用 :: 實例方法名
@Test
public void test2(){
Employee emp = new Employee(101, "張三", 18, 9999.99);
Supplier<String> sup = () -> emp.getName();
System.out.println(sup.get());
System.out.println("----------------------------------");
// getName方法與Supplier接口的get方法,入參相同、返回值類型相同
Supplier<String> sup2 = emp::getName;
System.out.println(sup2.get());
}
//類名 :: 靜態方法名
@Test
public void test3(){
BiFunction<Double, Double, Double> fun = (x, y) -> Math.max(x, y);
System.out.println(fun.apply(1.5, 22.2));
System.out.println("--------------------------------------------------");
// BiFunction的apply方法,同Math的max方法,入參類型相同,返回值類型相同,可以直接忽略的參數列表
BiFunction<Double, Double, Double> fun2 = Math::max;
System.out.println(fun2.apply(1.2, 1.5));
}
//類名 :: 實例方法名
@Test
public void test5(){
// BiPredicate接口的boolean test(T t, U u)方法
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abcde", "abcde"));
System.out.println("-----------------------------------------");
// 使用第一個參數調用equals方法,將第二個參數作爲equals的入參
BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));
System.out.println("-----------------------------------------");
// Function接口的R apply(T t)方法
Function<Employee, String> fun = (e) -> e.show();
System.out.println(fun.apply(new Employee()));
System.out.println("-----------------------------------------");
// 使用第一個參數一個Employee對象調用show方法
Function<Employee, String> fun2 = Employee::show;
System.out.println(fun2.apply(new Employee()));
}
//類名 :: 實例方法名
@Test
public void test5(){
// BiPredicate接口的boolean test(T t, U u)方法
BiPredicate<String, String> bp = (x, y) -> x.equals(y);
System.out.println(bp.test("abcde", "abcde"));
System.out.println("-----------------------------------------");
// 使用第一個參數調用equals方法,將第二個參數作爲equals的入參
BiPredicate<String, String> bp2 = String::equals;
System.out.println(bp2.test("abc", "abc"));
System.out.println("-----------------------------------------");
// Function接口的R apply(T t)方法
Function<Employee, String> fun = (e) -> e.show();
System.out.println(fun.apply(new Employee()));
System.out.println("-----------------------------------------");
// 使用第一個參數一個Employee對象調用show方法
Function<Employee, String> fun2 = Employee::show;
System.out.println(fun2.apply(new Employee()));
}
二、構造器引用 :構造器的參數列表,需要與函數式接口中參數列表保持一致!
1. 類名 :: new
2. 數組引用 類型[] :: new;
@Test
public void test6(){
//Supplier接口的T get();方法
Supplier<Employee> sup = () -> new Employee();
System.out.println(sup.get());
System.out.println("------------------------------------");
//自動匹配Employee的無參構造器
Supplier<Employee> sup2 = Employee::new;
System.out.println(sup2.get());
//BiFunction的R apply(T t, U u);方法,自動匹配參數類型是String, Integer的構造器
BiFunction<String, Integer, Employee> fun2 = Employee::new;
System.out.println(fun2.apply("小明", 28));
}
//數組引用
@Test
public void test8(){
Function<Integer, String[]> fun = (args) -> new String[args];
String[] strs = fun.apply(10);
System.out.println(strs.length);
System.out.println("--------------------------");
Function<Integer, Employee[]> fun2 = Employee[] :: new;
Employee[] emps = fun2.apply(20);
System.out.println(emps.length);
}
package com.wqh.demo.java8;
public class Employee {
private int id;
private String name;
private int age;
private double salary;
private Status status;
public Employee() {
}
public Employee(String name) {
this.name = name;
}
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public Employee(int id, String name, int age, double salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
public Employee(int id, String name, int age, double salary, Status status) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
this.status = status;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String show() {
return "測試方法引用!";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (age != other.age)
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
return false;
return true;
}
@Override
public String toString() {
return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status
+ "]";
}
public enum Status {
FREE, BUSY, VOCATION;
}
}