函數式接口
有且只有一個抽象方法的接口。
函數式接口,即適用於函數式編程場景的接口。而java中的函數式編程體現就是Lambda,所以函數式接口 就是可以適用於Lambda使用的接口。只要確保接口中有且只有一個抽象方法,而java中的Lambda才能順利進行推導。
格式
只要確保接口中有且僅有一個抽象方法即可:
修飾符 interface 接口名稱{
public abstract 返回值類型 方法名稱(可選參數信息);
//其他非抽象方法內容
}
由於接口當中抽象方法 public abstract是可以被省略的,所以定義一個函數式接口很簡單:
public interface MyFunctionInterface{
void myMethod();
}
@FunctionalInterface註解
與 @Override 註解的作用類似,Java 8中專門爲函數式接口引入了一個新的註解: @FunctionalInterface 。該註解可用於一個接口的定義上:
@FunctionalInterface
public interface MyFunctionInterface{
void myMethod();
}
一旦使用該註解來定義接口,編譯器將會被強制檢查該接口是否確實有且僅有一個抽象方法,否則將會報錯。需要注意的是,即使不使用此註解,只要滿足函數式接口的定義,這仍然是一個函數式 接口,使用起來都一樣。
自定義函數式接口
對於剛剛定義好的 MyFunctionalInterface 函數式接口,典型使用場景就是作爲方法的參數:
package com.demo.java.study7;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 13:48
* @description:
* @Version: 1.0
*/
public class Test {
// 使用自定義的函數式接口作爲方法參數
public static void doSomeThing(MyFunctionInterface my){
my.myMethod();// 調用自定義的函數式接口方法
}
public static void main(String[] args) {
//調用函數式接口的方法
doSomeThing(()->{
System.out.println("Lambda執行了");
});
}
}
執行結果
四大函數式接口
JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景,它們主要在 java.util.function 包中被提供。
下面是最簡單的幾個接口及使用示例。
Supplier接口
java.util.function.Supplier 接口僅包含一個無參的方法: T get() 。用來獲取一個泛型參數指定類型的對象數據。由於這是一個函數式接口,這也就意味着對應的Lambda表達式需要“對外提供”一個符合泛型類型的對象數據。
import java.util.function.Supplier;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 14:51
* @description:
* @Version: 1.0
*/
public class Test5 {
private static String getString(Supplier<String> supplier){
return supplier.get();
}
public static void main(String[] args) {
String msgA="hello";
String msgB="world";
String msgC="java";
System.out.println(getString(()->msgA+msgB+msgC));
}
}
練習:求數組元素最大值
使用 Supplier 接口作爲方法參數類型,通過Lambda表達式求出int數組中的最大值。提示:接口的泛型請使用java.lang.Integer 類。
import java.util.function.Supplier;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 14:55
* @description:
* @Version: 1.0
*/
public class Test6 {
/**
* @Param [supplier]
* @return java.lang.Integer
* @Author youjp
* @Description //TODO 獲取最大數
* @throw
**/
private static Integer getMax(Supplier<Integer> supplier) {
return supplier.get();
}
public static void main(String[] args) {
int arr[] = {2, 3, 44, 55, 8};
int maxNum = getMax(() -> {
int max = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= max) {
max = arr[i];
}
}
return max;
});
System.out.println(maxNum);
}
}
Consumer接口
java.util.function.Consumer 接口則正好與Supplier接口相反,它不是生產一個數據,而是消費一個數據,其數據類型由泛型決定。
抽象方法:accept
Consumer 接口中包含抽象方法 void accept(T t) ,意爲消費一個指定泛型的數據。基本使用如:
import java.util.function.Consumer;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 15:22
* @description:
* @Version: 1.0
*/
public class Test7 {
private static void consumeString(Consumer<String> function){
function.accept("hello");
}
public static void main(String[] args) {
consumeString(s -> System.out.println(s));
}
}
執行結果
默認方法:andThen
如果一個方法的參數和返回值全都是 Consumer 類型,那麼就可以實現效果:消費數據的時候,首先做一個操作,然後再做一個操作,實現組合。而這個方法就是 Consumer 接口中的default方法 andThen 。下面是JDK的源代碼:
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
備註: java.util.Objects 的 requireNonNull 靜態方法將會在參數爲null時主動拋出
NullPointerException 異常。這省去了重複編寫if語句和拋出空指針異常的麻煩。
要想實現組合,需要兩個或多個Lambda表達式即可,而 andThen 的語義正是“一步接一步”操作。例如兩個步驟組合的情況:
package com.demo.java.study7;
import java.util.function.Consumer;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 15:22
* @description:
* @Version: 1.0
*/
public class Test7 {
private static void consumeString(Consumer<String> one,Consumer<String> two){
one.andThen(two).accept("Hello");
}
public static void main(String[] args) {
//先轉大寫字母,再轉小寫字母
consumeString(
s -> System.out.println(s.toUpperCase()),
s-> System.out.println(s.toLowerCase()));
}
}
運行結果將會首先打印完全大寫的HELLO,然後打印完全小寫的hello。當然,通過鏈式寫法可以實現更多步驟的組合。
練習:格式化打印信息
下面的字符串數組當中存有多條信息,請按照格式“ 姓名:XX。性別:XX。 ”的格式將信息打印出來。要求將打印姓名的動作作爲第一個 Consumer 接口的Lambda實例,將打印性別的動作作爲第二個 Consumer 接口的Lambda實例,將兩個 Consumer 接口按照順序“拼接”到一起。
public static void main(String[] args) {
String[] array = { "迪麗熱巴,女", "古力娜扎,女", "馬爾扎哈,男" };
}
解答
import java.util.function.Consumer;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 15:53
* @description:
* @Version: 1.0
*/
public class Test8 {
private static void consumeString(Consumer<String> one,Consumer<String> two,String[] array){
for(String info:array){
one.andThen(two).accept(info);
}
}
public static void main(String[] args) {
String[] array = { "迪麗熱巴,女", "古力娜扎,女", "馬爾扎哈,男" };
consumeString(
s-> System.out.print("姓名:"+s.split(",")[0]),
s -> System.out.println(" 性別:"+s.split(",")[1]+"。"),array);
}
}
輸出:
Predicate接口
有時候我們需要對某種類型的數據進行判斷,從而得到一個boolean值結果。這時可以使用
java.util.function.Predicate 接口。
抽象方法:test
Predicate 接口中包含一個抽象方法: boolean test(T t) 。用於條件判斷的場景:
import java.util.function.Predicate;
public class Demo15PredicateTest {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.test("HelloWorld");
System.out.println("字符串很長嗎:" + veryLong);
}
public static void main(String[] args) {
method(s ‐> s.length() > 5);
}
}
條件判斷的標準是傳入的Lambda表達式邏輯,只要字符串長度大於5則認爲很長。
默認方法:and
既然是條件判斷,就會存在與、或、非三種常見的邏輯關係。其中將兩個 Predicate 條件使用“與”邏輯連接起來實現“並且”的效果時,可以使用default方法 and 。其JDK源碼爲:
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) ‐> test(t) && other.test(t);
}
如果要判斷一個字符串既要包含大寫“H”,又要包含大寫“W”,那麼:
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method(Predicate<String> one, Predicate<String> two) {
boolean isValid = one.and(two).test("Helloworld");
System.out.println("字符串符合要求嗎:" + isValid);
}
public static void main(String[] args) {
method(s ‐> s.contains("H"), s ‐> s.contains("W"));
}
}
默認方法:or
與 and 的“與”類似,默認方法 or 實現邏輯關係中的“或”。JDK源碼爲:
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) ‐> test(t) || other.test(t);
}
如果希望實現邏輯“字符串包含大寫H或者包含大寫W”,那麼代碼只需要將“and”修改爲“or”名稱即可,其他都不變:
import java.util.function.Predicate;
public class Demo16PredicateAnd {
private static void method(Predicate<String> one, Predicate<String> two) {
boolean isValid = one.or(two).test("Helloworld");
System.out.println("字符串符合要求嗎:" + isValid);
}
public static void main(String[] args) {
method(s ‐> s.contains("H"), s ‐> s.contains("W"));
}
}
默認方法:negate
與”、“或”已經瞭解了,剩下的“非”(取反)也會簡單。默認方法 negate 的JDK源代碼爲:
default Predicate<T> negate() {
return (t) ‐> !test(t);
}
從實現中很容易看出,它是執行了test方法之後,對結果boolean值進行“!”取反而已。一定要在 test 方法調用之前調用 negate 方法,正如 and 和 or 方法一樣:
import java.util.function.Predicate;
public class Demo17PredicateNegate {
private static void method(Predicate<String> predicate) {
boolean veryLong = predicate.negate().test("HelloWorld");
System.out.println("字符串很長嗎:" + veryLong);
}
public static void main(String[] args) {
method(s ‐> s.length() < 5);
}
}
練習:集合信息篩選 ** 比較常用
數組當中有多條“姓名+性別”的信息如下,請通過 Predicate 接口的拼裝將符合要求的字符串篩選到集合ArrayList 中,需要同時滿足兩個條件:
- 必須爲女生;
- 姓名爲4個字。
public class DemoPredicate {
public static void main(String[] args) {
String[] array = { "迪麗熱巴,女", "古力娜扎,女", "馬爾扎哈,男", "趙麗穎,女" };
}
}
解答
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 19:47
* @description:
* @Version: 1.0
*/
public class Test9 {
public static void main(String[] args) {
String[] array = { "迪麗熱巴,女", "古力娜扎,女", "馬爾扎哈,男", "趙麗穎,女" };
List<String> list= filter(s -> "女".equals(s.split(",")[1]),
s -> s.split(",")[0].length()==4
,array);
System.out.println(list);
}
private static List<String> filter(Predicate<String> one,Predicate<String> two,String[] array){
List<String> list=new ArrayList<>();
for(int i=0;i<array.length;i++){
if(one.and(two).test(array[i])){
list.add(array[i]);
}
}
return list;
}
}
執行結果:
Function接口
java.util.function.Function<T,R> 接口用來根據一個類型的數據得到另一個類型的數據,前者稱爲前置條件,後者稱爲後置條件。
抽象方法:apply
Function 接口中最主要的抽象方法爲: R apply(T t) ,根據類型T的參數獲取類型R的結果。
使用的場景例如:將 String 類型轉換爲 Integer 類型。
import java.util.function.Function;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 20:17
* @description:
* @Version: 1.0
*/
public class Test10 {
private static void method(Function<String,Integer> function){
int num=function.apply("10");
System.out.println(num+5);
}
public static void main(String[] args) {
method(s -> Integer.parseInt(s));
}
}
輸出結果爲15。
默認方法:andThen
Function 接口中有一個默認的 andThen 方法,用來進行組合操作。JDK源代碼如:
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
該方法同樣用於“先做什麼,再做什麼”的場景,和 Consumer 中的 andThen 差不多:
import java.util.function.Function;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 20:17
* @description:
* @Version: 1.0
*/
public class Test10 {
private static void method(Function<String,Integer> one,Function<Integer,Integer> two){
int num=one.andThen(two).apply("10"); //10*10=100
System.out.println(num+5); //100+5=105
}
public static void main(String[] args) {
method(s -> Integer.parseInt(s), s->s*=10); //先轉換爲數字,再乘以10
}
}
第一個操作是將字符串解析成爲int數字,第二個操作是乘以10。兩個操作通過 andThen 按照前後順序組合到了一起。
請注意,Function的前置條件泛型和後置條件泛型可以相同。
練習:自定義函數模型拼接
請使用 Function 進行函數模型的拼接,按照順序需要執行的多個函數操作爲:
String str = “趙麗穎,20”;
- 將字符串截取數字年齡部分,得到字符串;
- 將上一步的字符串轉換成爲int類型的數字;
- 將上一步的int數字累加100,得到結果int數字。
import java.util.function.Function;
/**
* @ClassName:
* @PackageName: com.demo.java.study7
* @author: youjp
* @create: 2020-02-15 20:17
* @description:
* @Version: 1.0
*/
public class Test10 {
private static void method(Function<String,String> one,Function<String,Integer> two,Function<Integer,Integer> three,String s){
int num=one.andThen(two).andThen(three).apply(s);
System.out.println(num);
}
public static void main(String[] args) {
String str = "趙麗穎,20";
//1. 將字符串截取數字年齡部分,得到字符串;
// 2. 將上一步的字符串轉換成爲int類型的數字;
// 3. 將上一步的int數字累加100,得到結果int數字。
method(s -> s.split(",")[1] ,
s -> Integer.parseInt(s),
s->s+=100,
str
);
}
}
執行結果: