前言
★ 這里是小冷的博客
? 優質技術好文見專欄
個人公眾號,分享一些技術上的文章,以及遇到的坑
當前系列:Java8 新特性 系列
源代碼 git 倉庫 代碼Git 倉庫地址
Java8 新特性
函式式介面(Functional)
通過上面的 Lambda運算式的學習,我們認識了 新的語法,支持這種語法的介面
- 只包含一個抽象方法的介面,稱為函式式介面
- 你只可以通過 Lambda運算式,來創建該介面的物件,(Lambda運算式拋出一個拋出一個檢查例外(即,運行時例外),這個衣長需要在目標介面的抽象方法上進行宣告)
- 我們可以在介面上使用@FunctionalInterface注解,這樣做可以檢查這個介面是不是函式式介面,同時javadoc也會包含一條宣告說明這個介面是一個函式式介面,
- java.util.funcion包下定義了Java8豐富的函式式介面
Lambda的運算式本質其實就是函式式介面的實體
什么是函式式介面呢?
Runnable介面就是一個很典型的函式式介面
@FunctionalInterface
public interface Runnable {
public abstract void run();
}
這里我們自己定一個
@FunctionalInterface
public interface MyinterFace {
void method1();
}
Java內置四大核心函式式介面
| 函式式介面 | 引數型別 | 回傳型別 | 用途 |
|---|---|---|---|
| Consumer 消費型介面 | T | void | 對型別為t的物件應用操作,包含方法void accept(T,t) |
| Supperlier供給型介面 | 無 | T | 回傳型別為T的物件,包含方法 T get() |
| Function<T,R> | T | R | 對型別為T的物件應用操作,并回傳結果,結果是R型別的物件,包含方法 R apply(T t) |
| Predicate | T | boolean | 確定型別為T的物件是否滿足某個約束,并回傳boolean值,包含方法 boolean test(T t) |
理論+實踐
我們以 Consumer 與 Predicate舉例子
/**
* @author : <h2>冷環淵</h2>
* @date : 2021/12/11
* @context: <h4>
* 消費型介面 Consumer<T> Accept(T t)
* 供給型介面 Supplier<T> T get()
* 函式式介面 Function<T> R apply(T t)
* 斷定型介面 Predicate<T> boolean test(T t)
* </h4>
*/
public class LambdaTest2 {
/**
* @author 冷環淵 Doomwatcher
* @context: Consumer<T> 使用
* @date: 2021/12/11 14:37
* @param
* @return: void
*/
@Test
public void Test1() {
happyTime(500, new Consumer<Double>() {
@Override
public void accept(Double aDouble) {
System.out.println("天上人間的水今天很貴:" + aDouble);
}
});
System.out.println("****************************");
happyTime(400, money -> System.out.println("學習太累了,去天上人間買了瓶礦泉水,價格為:" + money));
}
/**
* @author: 冷環淵 Doomwatcher
* @context:
* @date: 2021/12/11 14:33
* @param money
* @param con
* @return void
*/
public void happyTime(double money, Consumer<Double> con) {
con.accept(money);
}
/**
* @author 冷環淵 Doomwatcher
* @context: 斷言 Predicate 的使用
* @date: 2021/12/11 14:39
* @param
* @return: void
*/
@Test
public void Test2() {
//傳統寫法
List<String> filterList = Arrays.asList("北京", "天津", "南京", "東京", "江南");
List<String> filterStr = filterString(filterList, new Predicate<String>() {
@Override
public boolean test(String s) {
return s.contains("京");
}
});
System.out.println(filterStr);
System.out.println("*******************************");
// Lambda運算式 寫法
List<String> filterList1 = Arrays.asList("北京", "天津", "南京", "東京", "江南");
List<String> filterStr1 = filterString(filterList1, s -> s.contains("京"));
System.out.println(filterStr1);
}
/**
* @author 冷環淵 Doomwatcher
* @context:
* @date: 2021/12/11 14:49
* @param list
* @param pre
* @return: java.util.List<java.lang.String>
*/
public List<String> filterString(List<String> list, Predicate<String> pre) {
ArrayList<String> filterlist = new ArrayList<>();
for (String s : list) {
if (pre.test(s)) {
filterlist.add(s);
}
}
return filterlist;
}
}
方法參考與構造器參考
方法參考
- 當前要傳遞給 Lambda體的操作,已經有了實作的方法了,可以使用方法參考
- 方法參考可以看做是Lambda運算式的深層次表達,換句話說,方法參考就是Lambda運算式,只不過和之前我們自己撰寫不同,這里通過方法的名字來指向一個方法,可以認為是Lambda運算式的一種語法糖
- 要求:實作介面的抽象方法的引數串列和回傳值型別,必須與方法參考的方法的引數串列和回傳值保持一致
- 格式:使用運算子“::”將類或者物件與方法名字分開來
- 如下是三種主要的使用情況
- 物件::實體方法名
- 類::靜態方法名
- 類::實體方法名
coding
準備兩個類 一個是list集合,一個是物件
Employee get/set 和 tostring 為防止無用篇幅過長,這里我們簡寫只看一下物件屬性即可
package Lambda.MethodReferences;
/**
*
* @author : <h2>冷環淵</h2>
* @date : 2021/12/11
* @context:<h4>提供用于測驗的物件</h4>
*/
public class Employee {
private int id;
private String name;
private int age;
private double salary;
\
}
EmployeeData
package Lambda.MethodReferences;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author : <h2>冷環淵</h2>
* @date : 2021/12/11
* @context:<h4>提供用于測驗的資料</h4>
*/
public class EmployeeData {
public static List<Employee> getEmployees() {
List<Employee> list = new ArrayList<>();
list.add(new Employee(1001, "馬化騰", 34, 6000.38));
list.add(new Employee(1002, "馬云", 12, 9876.12));
list.add(new Employee(1003, "劉強東", 33, 3000.82));
list.add(new Employee(1004, "雷軍", 26, 7657.37));
list.add(new Employee(1005, "李彥宏", 65, 5555.32));
list.add(new Employee(1006, "比爾蓋茨", 42, 9500.43));
list.add(new Employee(1007, "任正非", 26, 4333.32));
list.add(new Employee(1008, "扎克伯格", 35, 2500.32));
return list;
}
}
方法參考 test
/**
* @author : <h2>冷環淵</h2>
* @date : 2021/12/11
* @context:<h4>
* 方法參考的使用
*
* 1.使用情境:當要傳遞給Lambda體的操作,已經有實作的方法了,可以使用方法參考!
* 2.方法參考,本質上就是Lambda運算式,而Lambda運算式作為函式式介面的實體,所以
* 方法參考,也是函式式介面的實體,
* 3. 使用格式: 類(或物件) :: 方法名
* 4. 具體分為如下的三種情況:
* 情況1 物件 :: 非靜態方法
* 情況2 類 :: 靜態方法
* 情況3 類 :: 非靜態方法
* 5. 方法參考使用的要求:要求介面中的抽象方法的形參串列和回傳值型別與方法參考的方法的
* 形參串列和回傳值型別相同!(針對于情況1和情況2)
*
* </h4>
*
*/
public class MethodRefTest {
// 情況一:物件 :: 實體方法
//Consumer中的void accept(T t)
//PrintStream中的void println(T t)
@Test
public void test1() {
Consumer<String> con1 = str -> System.out.println(str);
con1.accept("北京");
System.out.println("*******************");
PrintStream ps = System.out;
Consumer<String> con2 = ps::println;
con2.accept("beijing");
}
//Supplier中的T get()
//Employee中的String getName()
@Test
public void test2() {
Employee emp = new Employee(1001, "Tom", 23, 5600);
Supplier<String> sup1 = () -> emp.getName();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<String> sup2 = emp::getName;
System.out.println(sup2.get());
}
// 情況二:類 :: 靜態方法
//Comparator中的int compare(T t1,T t2)
//Integer中的int compare(T t1,T t2)
@Test
public void test3() {
Comparator<Integer> com1 = (t1, t2) -> Integer.compare(t1, t2);
System.out.println(com1.compare(12, 21));
System.out.println("*******************");
Comparator<Integer> com2 = Integer::compare;
System.out.println(com2.compare(12, 3));
}
//Function中的R apply(T t)
//Math中的Long round(Double d)
@Test
public void test4() {
Function<Double, Long> func = new Function<Double, Long>() {
@Override
public Long apply(Double d) {
return Math.round(d);
}
};
System.out.println("*******************");
Function<Double, Long> func1 = d -> Math.round(d);
System.out.println(func1.apply(12.3));
System.out.println("*******************");
Function<Double, Long> func2 = Math::round;
System.out.println(func2.apply(12.6));
}
// 情況三:類 :: 實體方法 (有難度)
// Comparator中的int comapre(T t1,T t2)
// String中的int t1.compareTo(t2)
@Test
public void test5() {
Comparator<String> com1 = (s1, s2) -> s1.compareTo(s2);
System.out.println(com1.compare("abc", "abd"));
System.out.println("*******************");
Comparator<String> com2 = String::compareTo;
System.out.println(com2.compare("abd", "abm"));
}
//BiPredicate中的boolean test(T t1, T t2);
//String中的boolean t1.equals(t2)
@Test
public void test6() {
BiPredicate<String, String> pre1 = (s1, s2) -> s1.equals(s2);
System.out.println(pre1.test("abc", "abc"));
System.out.println("*******************");
BiPredicate<String, String> pre2 = String::equals;
System.out.println(pre2.test("abc", "abd"));
}
// Function中的R apply(T t)
// Employee中的String getName();
@Test
public void test7() {
Employee employee = new Employee(1001, "Jerry", 23, 6000);
Function<Employee, String> func1 = e -> e.getName();
System.out.println(func1.apply(employee));
System.out.println("*******************");
Function<Employee, String> func2 = Employee::getName;
System.out.println(func2.apply(employee));
}
}
構造方法參考
通過 簡化 的方式,來呼叫不同的構造器
一、構造器參考
- 和方法參考類似,函式式介面的抽象方法的形參串列和構造器的形參串列一致,
- 抽象方法的回傳值型別即為構造器所屬的類的型別
二、陣列參考
- 大家可以把陣列看做是一個特殊的類,則寫法與構造器參考一致,
/**
*
* @author : <h2>冷環淵</h2>
* @date : 2021/12/11
* @context:<h4>
*
* 一、構造器參考
* 和方法參考類似,函式式介面的抽象方法的形參串列和構造器的形參串列一致,
* 抽象方法的回傳值型別即為構造器所屬的類的型別
*
* 二、陣列參考
* 大家可以把陣列看做是一個特殊的類,則寫法與構造器參考一致,
* </h4>
*/
public class ConstructorRefTest {
//構造器參考
//Supplier中的T get()
//Employee的空參構造器:Employee()
@Test
public void test1() {
Supplier<Employee> sup = new Supplier<Employee>() {
@Override
public Employee get() {
return new Employee();
}
};
System.out.println("*******************");
Supplier<Employee> sup1 = () -> new Employee();
System.out.println(sup1.get());
System.out.println("*******************");
Supplier<Employee> sup2 = Employee::new;
System.out.println(sup2.get());
}
//Function中的R apply(T t)
@Test
public void test2() {
Function<Integer, Employee> func1 = id -> new Employee(id);
Employee employee = func1.apply(1001);
System.out.println(employee);
System.out.println("*******************");
Function<Integer, Employee> func2 = Employee::new;
Employee employee1 = func2.apply(1002);
System.out.println(employee1);
}
//BiFunction中的R apply(T t,U u)
@Test
public void test3() {
BiFunction<Integer, String, Employee> func1 = (id, name) -> new Employee(id, name);
System.out.println(func1.apply(1001, "Tom"));
System.out.println("*******************");
BiFunction<Integer, String, Employee> func2 = Employee::new;
System.out.println(func2.apply(1002, "Tom"));
}
//陣列參考
//Function中的R apply(T t)
@Test
public void test4() {
Function<Integer, String[]> func1 = length -> new String[length];
String[] arr1 = func1.apply(5);
System.out.println(Arrays.toString(arr1));
System.out.println("*******************");
Function<Integer, String[]> func2 = String[]::new;
String[] arr2 = func2.apply(10);
System.out.println(Arrays.toString(arr2));
}
}
總結
- 全新的語法帶來了很多的便捷,理解起來可能相對麻煩
- 這里在改變語法為Lambda的時候,可以自己找找可以省去,那一些部分
- 思考,為什么構造器參考可以根據數量和型別去找到對應的構造器
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/379469.html
標籤:java
