1. 函數式接口
1.1 概念
函數式接口在Java中是指,有且僅有一個抽象方法的接口
。
可以適用於Lambda使用的接口
1.2 格式
修飾符 interface 接口名稱 {
public abstract 返回值類型 方法名稱(可選參數信息);
//其他抽象方法內容
}
public abstract可以省略
。
例子:
public interface MyFunctionalInterface {
public abstract void method();
}
1.3 @FunctionalInterface註解
與@Override註解作用類似,Java8中專門爲函數式接口引入了一個新的註解:@FunctionalInterface,該註解可用於一個接口的定義上。
- @Override註解
作用:檢查方法是否爲重寫的方法
是:編譯成功
否:編譯失敗
- @FunctionalInterface註解
作用:可以檢測接口是否是一個函數式接口
是:編譯成功
否:編譯失敗(接口中沒有抽象方法或者抽象方法的個數多餘1個)
例子:
函數式接口:MyFunctionalInterface.java
/**
* @FunctionalInterface註解
* 作用:可以檢測接口是否是一個函數式接口
* 是:編譯成功
* 否:編譯失敗(接口中沒有抽象方法或者抽象方法的個數多餘1個)
* @author kevin
*
*/
@FunctionalInterface
public interface MyFunctionalInterface {
public abstract void method();
}
接口實現類:MyFunctionalInterfaceImpl.java
public class MyFunctionalInterfaceImpl implements MyFunctionalInterface {
@Override
public void method() {
System.out.println("MyFunctionalInterfaceImpl--method()--");
}
}
測試類:TestMyFunctionalInterface.java
/**
* 函數式接口的使用:一般可作爲方法的參數和返回值類型
* @author kevin
*
*/
public class TestMyFunctionalInterface {
//定義一個方法,參數使用函數式接口MyFunctionalInterface
public static void show(MyFunctionalInterface myInterface) {
myInterface.method();
}
public static void main(String[] args) {
//調用show方法,方法的參數是一個接口,所以可以傳遞接口的實現類對象
show(new MyFunctionalInterfaceImpl());
//調用show方法,方法的參數是一個接口,所以可以傳遞接口的匿名內部類
show(new MyFunctionalInterface() {
@Override
public void method() {
System.out.println("使用匿名內部類重寫接口中的抽象方法");
}
});
//調用show方法,方法參數是一個函數式接口,所以我們可以用Lambda表達式()-{}
show(() -> {
System.out.println("使用Lambda表達式重寫接口中的抽象方法");
});
//簡化Lambda表達式
show(() -> System.out.println("使用Lambda表達式重寫接口中的抽象方法"));
}
}
2. 函數式編程
2.1 Lambda的延遲執行
Lambda表達式是延遲執行的,可以避免代碼被執行後,結果卻不一定被使用所造成的性能浪費。
- 性能浪費的例子
/**
* 日誌案例
*
* 以下代碼存在的性能浪費的問題
* 調用showLog方法,傳遞的第二個參數是一個拼接後的字符串
* 先把字符串拼接好,然後再調用showLog方法
* showLog方法中如果傳遞的日誌等級不是1級
* 那麼就不會輸出拼接後的字符串
* 所以感覺字符串白拼接了,存在了浪費
* @author kevin
*
*/
public class TestLogger {
//定義一個根據日誌的級別,顯示日誌信息的方法
public static void showLog(int level, String msg) {
//對日誌等級進行判斷,如果是1級別,那麼輸出日誌信息
if(level == 1) {
System.out.println(msg);
}
}
public static void main(String[] args) {
//定義三個日誌信息
String msg1 = "Hello";
String msg2 = "World";
String msg3 = "Java";
showLog(2, msg1+msg2+msg3);
}
}
- 使用Lambad優化的例子
Lambda的使用前提,必須存在函數式接口
,所以先定義一個函數式接口.
MessageBuilder.java
/**
* 函數式接口,有且只有一個抽象方法的接口,稱之爲函數式接口
* 當然接口中可以包含其他的方法(默認,靜態,私有等)
* @author kevin
*
*/
@FunctionalInterface
public interface MessageBuilder {
//定義一個抽象方法,返回被拼接的信息
public abstract String builderMessage();
}
測試類:TestLambdaLogger.java
/**
* 使用Lambda優化日誌案例
* Lambda特點:延遲加載
* Lambda的使用前提,必須存在函數式接口
* @author kevin
*
*/
public class TestLambdaLogger {
//定義一個顯示日誌的方法,方法的參數傳遞日誌的等級和MessageBuilder接口
public static void showLog(int level, MessageBuilder mb) {
//對日誌的等級進行判斷,如果是1級,則調用MessageBuilder接口中的builderMessage方法
if(level == 1) {
System.out.println(mb.builderMessage());
}
}
public static void main(String[] args) {
String msg1 = "Hello";
String msg2 = "World";
String msg3 = "Java";
/*showLog(1, () -> {
return msg1+msg2+msg3;
});*/
/**
* 使用Lambda表達式作爲參數傳遞,僅僅是把參數傳遞到showLog方法中
* 只有滿足條件,日誌等級是1級
* 纔會調用接口MessageBuilder中的方法builderMessage
* 纔會進行字符串的拼接
*如果添加不滿足,日誌的等級不是1級
* 那麼MessageBuilder接口中的方法builderMessage也不會執行
* 所以拼接字符串的代碼也不會執行
*所以不存在性能的浪費
*/
showLog(2, () -> {
System.out.println("不滿足條件不執行");
return msg1+msg2+msg3;
});
}
}
2.2 使用Lambda作爲參數和返回值
如果方法的參數是一個函數式接口類型,那麼就可以使用Lambda表達式進行替代。使用Lambda表達式作爲方法參數,其實就是使用函數式接口作爲方法參數。
TestRunnable1.java
/**
* 例如java.lang.Runnable接口就是一個函數式接口
* 假設有一個startThread方法使用該接口作爲參數,那麼就可以使用Lambda進行傳參
* 這種情況其實和Thread類的構造方法參數爲Runnable沒有本質區別
* @author kevin
*
*/
public class TestRunnable1 {
//定義一個startThread方法,方法的參數使用函數式接口Runnable
public static void startThread(Runnable run) {
//開啓多線程
new Thread(run).start();
}
public static void main(String[] args) {
//調用startThread方法,方法的參數是一個接口,那麼我們可以傳遞這個接口的匿名內部類
startThread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+"線程啓動了");
}
});
//調用startThread方法,方法的參數是一個函數式接口,所以可以傳遞Lambda表達式
startThread(() -> {
System.out.println(Thread.currentThread().getName()+"-->"+"線程啓動了");
});
//優化Lambda表達式
startThread(() -> System.out.println(Thread.currentThread().getName()+"-->"+"線程啓動了"));
}
}
如果一個方法的返回值是一個函數式接口,那麼就可以直接返回一個Lambda表達式。
TestComparator1.java
/**
* 如果一個方法的返回值類型是一個函數式接口,那麼就可以直接返回一個Lambda表達式
* 需要通過一個方法獲取一個java.util.Comparator接口類型的對象作爲排序器時,就可以調該方法獲取
* @author kevin
*
*/
public class TestComparator1 {
public static Comparator<String> getComparator(){
/*return new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
// 按照字符串的降序排序
return o2.length() - o1.length();
}
};*/
//方法的返回值類型是一個函數式接口,所以我們可以返回一個Lambda表達式
/*return (String o1, String o2) -> {
return o2.length() - o1.length();
};*/
//優化Lambda
return (o1, o2) -> o2.length() - o1.length();
}
public static void main(String[] args) {
String[] arr = {"aaa","b","cccccc","ddddddd"};
System.out.println(Arrays.toString(arr));
Arrays.sort(arr, getComparator());
System.out.println(Arrays.toString(arr));
}
}
3. 常用的函數式接口
JDK提供了大量常用的函數式接口以豐富Lambda的典型使用場景,主要在java.util.function包中。
3.1 Supplier接口
java.util.function.Supplier 接口僅包含一個無參的方法:T get()。用來獲取一個泛型參數指定類型的對象數據。
Supplier<T>接口被稱之爲生產型接口
,指定接口的泛型是什麼類型,那麼接口中的get方法就會產生什麼類型的數據。
public class TestSupplier1 {
public static String getString(Supplier<String> sup) {
return sup.get();
}
public static void main(String[] args) {
String s = getString(() -> {
return "你還,世界!";
});
System.out.println(s);
//優化Lambda表達式
String s1 = getString(() -> "Hello World!");
System.out.println(s1);
}
}
3.1.1 例子:求數組元素最大值
/**
* 求數組元素最大值
* 使用Supplier接口作爲方法的參數類型,通過Lambda表達式求出int數組中最大值
* @author kevin
*
*/
public class TestSupplier2 {
//定義一個方法,用於獲取int類型數組中元素的最大值,方法的參數傳遞Supplier接口,泛型使用Integer
public static int getMax(Supplier<Integer> sup) {
return sup.get();
}
public static void main(String[] args) {
int[] arr = {100,0,-32,87,98,22,-25,188};
int maxValue = getMax(() -> {
int max = arr[0];
for (int i : arr) {
if(i > max) {
max = i;
}
}
return max;
});
System.out.println("數組中元素的最大值是:"+maxValue);
}
}
3.2 Consumer接口
java.util.function.Consumer接口正好與Supplier接口相反,它不是生產一個數據,而是消費一個數據,其數據類型由泛型決定。
3.2.1 抽象方法:accept
Consumer
接口中包含抽象方法void accept(T t)
,意爲消費一個指定泛型的數據。
/**
* java.util.function.Consumer<T>接口正好與Supplier接口相反,
* 它不是生產一個數據,而是消費一個數據,其數據類型由泛型決定。
* Consumer接口中包含抽象方法void accept(T t),意爲消費一個指定泛型的數據。
*
* Consumer接口是一個消費型接口,泛型執行什麼類型,就可以使用accept方法消費什麼類型的數據
* 至於具體怎麼消費(使用),需要自定義(輸出,計算...)
* @author kevin
*
*/
public class TestConsumer1 {
/**
* 定義一個方法
* 方法的參數傳遞一個字符串的姓名
* 方法的參數傳遞Consumer接口,泛型使用String
* 可以使用Consumer接口消費字符串的姓名
* @param name
* @param con
*/
public static void method(String name, Consumer<String> con) {
con.accept(name);
}
public static void main(String[] args) {
method("Kevin", (String name) -> {
//對傳遞的字符串進行消費
//消費方式:直接輸出字符串
//System.out.println(name);
//消費方式:把字符串進行反轉輸出
String reName = new StringBuffer(name).reverse().toString();
System.out.println(reName);
});
}
}
3.2.2 默認方法:andThen
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語句和拋出空指針異常的麻煩。
public class TestConsumer2 {
public static void method(String s, Consumer<String> con1, Consumer<String> con2) {
/*con1.accept(s);
con2.accept(s);*/
//使用andThen方法,把兩個Consumer接口連接到一起,在消費數據
con1.andThen(con2).accept(s);//con1連接con2,先執行con1消費數據,在執行con2消費數據
}
public static void main(String[] args) {
method("Hello", (t) -> {
//消費方式:把字符串轉換成大寫輸出
System.out.println(t.toUpperCase());
}, (t) -> {
//消費方式:把字符串轉換成小寫輸出
System.out.println(t.toLowerCase());
});
}
}
3.2.3 例子:格式化打印
/**
* 字符串數組當中存有多條信息,請按照格式“姓名:xx。性別:xx。”的格式將信息打印出來。
* 要求將打印姓名的動作作爲第一個Consumer接口的Lambda實例,
* 將打印性別的動作作爲第二個Consumer接口的Lambda實例,
* 將兩個Consumer接口按照順序“拼接”到一起。
* @author kevin
*
*/
public class TestConsumer3 {
public static void printInfo(String[] arr, Consumer<String> con1, Consumer<String> con2) {
//遍歷字符串數組
for (String str : arr) {
con1.andThen(con2).accept(str);
}
}
public static void main(String[] args) {
//定義一個字符串類型的數組
String[] arr = {"迪麗熱巴,女","古力娜扎,女","馬爾扎哈,男"};
printInfo(arr, (str) -> {
String name = str.split(",")[0];
System.out.println("姓名:"+name);
}, (str) -> {
String sex = str.split(",")[1];
System.out.println("性別:"+sex);
});
}
}
輸出結果:
姓名:迪麗熱巴
性別:女
姓名:古力娜扎
性別:女
姓名:馬爾扎哈
性別:男
3.3 Predicate接口
當需要對某種類型的數據進行判斷,從而得到一個boolean值結果。這時可以使用java.util.function.Predicate<T>
接口。
3.3.1 抽象方法:test
Predicate
接口中包含一個抽象方法:boolean test(T t)
。用於條件判斷場景
/**
* java.util.function.Predicate<T>接口
* 作用:對某種數據類型的數據進行判斷,結果返回一個boolean值
*
* Predicate接口中包含一個抽象方法:
* boolean test(T t):用來指定數據類型數據進行判斷的方法
* 結果:
* 符合條件,返回true
* 不符合條件,返回false
* @author kevin
*
*/
public class TestPredicate {
public static boolean checkString(String s, Predicate<String> pre) {
return pre.test(s);
}
public static void main(String[] args) {
String s = "abcdef";
/*boolean b = checkString(s, (String str) -> {
return str.length() > 5;
});*/
//優化Lambda表達式
boolean b = checkString(s, str -> str.length() > 5);
System.out.println(b);//true
}
}
3.3.2 默認方法:and
既然是條件判斷,就會存在與、或、非三種常見的邏輯關係,其中將兩個Predicate
條件使用“與”邏輯連接起來實現“並且”的效果時,可以使用default方法and,其JDK源碼爲:
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
/**
* 邏輯表達式,可以連接多個判斷的條件
* &&: 與運算符,有false則false
* ||: 或運算符,有true則true
* !: 非(取反)運算符,非真則假,非假則真
*
* 需求:判斷一個字符串
* 1.判斷字符串長度是否大於5
* 2.判斷字符串中是否包含b
* 兩個條件必須同時滿足,我們可以使用&&運算符連接兩個條件
* @author kevin
*
*/
public class TestPredicate2 {
public static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2) {
//return pre1.test(s) && pre2.test(s);
return pre1.and(pre2).test(s);
}
public static void main(String[] args) {
String s = "bcdeff";
boolean b = checkString(s, (String str) -> {
return str.length() > 5;
}, (String str) -> {
return str.contains("b");
});
System.out.println(b);//true
}
}
3.3.3 默認方法:or
與and
的“與”類似,默認方法or
實現邏輯關係中的“或”。JDK源碼爲:
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
public class TestPredicate3 {
public static boolean checkString(String s, Predicate<String> pre1, Predicate<String> pre2) {
//return pre1.test(s) || pre2.test(s);
return pre1.or(pre2).test(s);
}
public static void main(String[] args) {
String s = "bcdeff";
boolean b = checkString(s, (String str) -> {
return str.length() > 5;
}, (String str) -> {
return str.contains("a");
});
System.out.println(b);//true
}
}
3.3.4 默認方法:negate
"非"即取反,默認方法negate
的JDK源碼爲:
default Predicate<T> negate() {
return (t) -> !test(t);
}
public class TestPredicate4 {
public static boolean checkString(String s, Predicate<String> pre) {
//return !pre.test(s);
return pre.negate().test(s);
}
public static void main(String[] args) {
String s = "abc";
boolean b = checkString(s, (String str) -> {
return str.length()>5;
});
System.out.println(b);//true
}
}
3.3.5 例子:集合信息篩選
/**
* 集合信息篩選
* 數組當中有多條“姓名+性別”的信息如下:
* String[] arr = {"迪麗熱巴,女","古力娜扎,女","馬爾扎哈,男","趙麗穎,女"};
* 請通過Predicate接口的拼裝將符合要求的字符串篩選到集合ArrayList中,
* 需同時滿足兩個條件:
* 1.必須爲女生
* 2.姓名爲4個字
* @author kevin
*
*/
public class TestPredicate5 {
public static ArrayList<String> filter(String[] arr, Predicate<String> pre1, Predicate<String> pre2){
ArrayList<String> list = new ArrayList<>();
for (String s : arr) {
boolean b = pre1.and(pre2).test(s);
if(b) {
list.add(s);
}
}
return list;
}
public static void main(String[] args) {
String[] array = {"迪麗熱巴,女","古力娜扎,女","馬爾扎哈,男","趙麗穎,女"};
ArrayList<String> list = filter(array, (String s) -> {
return s.split(",")[1].equals("女");
}, (String s) -> {
return s.split(",")[0].length()==4;
});
for(String s : list) {
System.out.println(s);
}
}
}
3.4 Function接口
java.util.function.Function<T,R>
接口用來根據一個類型的數據得到另一個類型的數據,前者稱爲前置條件,後者稱爲後置條件。
3.3.1 抽象方法:apply
Function
接口中最主要的抽象方法爲:R apply(T t)
,根據類型T的參數獲取類型R的結果。
/**
* 將String類型轉換爲Integer類型
* @author kevin
*
*/
public class TestFunction {
/**
* 定義一個方法
* 方法的參數傳遞一個字符串類型的整數
* 方法的參數傳遞一個Function接口,泛型使用<String, Integer>
* 使用Function接口中的方法apply,把字符串類型的整數,轉換爲Integer類型的整數
* @param s
* @param fun
*/
public static void change(String s, Function<String, Integer> fun) {
Integer in = fun.apply(s);
System.out.println(s);
}
public static void main(String[] args) {
//定義一個字符串類型的整數
String s = "1234";
//調用change方法,傳遞字符串類型的整數和Lambda表達式
change(s, (String str) -> {
//把字符串類型的整數,轉換爲Integer類型的整數返回
return Integer.parseInt(str);
});
//優化Lambda
change(s, str -> Integer.parseInt(str));
}
}
3.3.2 默認方法: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));
}
該方法用於“先做什麼,再做什麼”場景
/**
* Function接口中的默認方法andThen: 用來進行組合操作
*
* 需求:
* 把String類型的"123",轉換爲Integer類型,把轉換後的結果加10
* 把增加之後的Integer類型的數據,轉換爲String類型
*
* 分析:
* 轉換了兩次
* 第一次是把String類型轉換爲Integer類型
* 所以我們可以使用Function<String,Integer> fun1
* Integer = fun1.apply("123")+10;
* 第二次是把Integer類型轉換爲String類型
* 所以我們可以使用Function<Integer,String> fun2
* String s = fun2.apply(i);
* 我們可以使用andThen方法,把兩次轉換組合在一起使用
* String s = fun1.andThen(fun2).apply(i)
* @author kevin
*
*/
public class TestFunction2 {
/**
* 定義一個方法
* 參數傳一個字符串類型的整數
* 參數傳遞兩個Function接口
* 一個泛型使用Function<String,Integer>
* 一個泛型使用Function<Integer,String>
* @param s
* @param fun1
* @param fun2
*/
public static void change(String s, Function<String, Integer> fun1, Function<Integer, String> fun2) {
String ss = fun1.andThen(fun2).apply(s);
System.out.println(ss);
}
public static void main(String[] args) {
//定義一個字符串類型的整數
String s = "123";
//使用change方法,傳遞字符串和兩個Lambda表達式
change(s, (String str) -> {
//將字符串轉換爲整數+10
return Integer.parseInt(str)+10;
}, (Integer i) -> {
//把整數轉換爲字符串
return i+"";
});
//優化Lambda表達式
change(s, str -> Integer.parseInt(str)+10, i -> i+"");
}
}
3.3.3 自定義函數模型拼接
/**
* 自定義函數模型拼接
*
* 使用Function進行函數模型的拼接,按照順序需要執行的多個函數操作爲:
* String str = "趙麗穎,20";
*
* 分析:
* 1.將字符串截取數字年齡部分,得到字符串
* Function<String,String> "趙麗穎,20" -> "20"
* 2.將上一步的字符串轉換成爲int類型的數字
* Function<String,Integer> "20" -> 20
* 3.將上一步的int數字累加到100,得到結果int數字
* Function<Integer,Integer> 20 -> 120
* @author kevin
*
*/
public class TestFunction3 {
/*
* 定義一個方法
* 參數傳遞包含姓名和年齡的字符串
* 參數再傳遞3個Function接口用於類型轉換
*/
public static int change(String s, Function<String, String> fun1, Function<String, Integer> fun2, Function<Integer, Integer> fun3) {
//使用andThen方法把三個轉換組合到一起
return fun1.andThen(fun2).andThen(fun3).apply(s);
}
public static void main(String[] args) {
//定義一個字符串
String str = "趙麗穎,20";
//調用change方法,參數傳遞字符串和3個Lambda表達式
int num = change(str, (String s) -> {
return s.split(",")[1];
}, (String s) -> {
return Integer.parseInt(s);
}, (Integer i) -> {
return i+100;
});
System.out.println(num);
}
}