在一起來學Java8(二)——Lambda表達式
中我們學習了Lambda表達式的基本用法,現在來了解下複合Lambda。
Lambda表達式的的書寫離不開函數式接口,複合Lambda的意思是在使用Lambda表達式實現函數式接口抽象方法後,還可以再次調用接口的其它方法,因爲從Java8開始,接口中可以包含默認實現的方法。關於接口默認實現方法
將會在後面章節詳細闡述。
常見的複合Lambda常見的有以下幾類:
- 比較器複合,對應的函數式接口:Comparator
- 謂詞複合,對應的函數式接口:Predicate
- 函數複合,對應的函數式接口:Function
比較器複合
先來看下Comparator接口的常見用法,針對商品價格從低到高排序
package learn.java8.ch4;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
class Goods {
private String name;
private int price;
public Goods(String name, int price) {
super();
this.name = name;
this.price = price;
}
省略get set
}
public class ComparatorTest {
public static void main(String[] args) {
List<Goods> list = Arrays.asList(
new Goods("mete30", 3999),
new Goods("mete30 pro", 4999),
new Goods("redmi k20", 2999),
new Goods("iqoo", 2999),
new Goods("iphone11", 5000)
);
Comparator<Goods> comparatorForPrice = (Goods goods1, Goods goods2) -> {
return Integer.compare(goods1.getPrice(), goods2.getPrice());
};
list.sort(comparatorForPrice);
System.out.println(list);
}
}
這裏是根據價格從低到高排序,我們可以再加一個需求,如果價格一樣,再根據商品名稱排序。那麼代碼可以這樣寫:
public static void main(String[] args) {
List<Goods> list = Arrays.asList(new Goods("mete30", 3999), new Goods("mete30 pro", 4999),
new Goods("redmi k20", 2999), new Goods("iqoo", 2999), new Goods("iphone11", 5000));
Comparator<Goods> comparatorForPrice = (Goods goods1, Goods goods2) -> {
return Integer.compare(goods1.getPrice(), goods2.getPrice());
};
Comparator<Goods> comparatorForName = (Goods goods1, Goods goods2) -> {
return goods1.getName().compareTo(goods2.getName());
};
// 把兩個函數式接口進行復合,組成一個新的接口
Comparator<Goods> finalComparator = comparatorForPrice.thenComparing(comparatorForName);
list.sort(finalComparator);
System.out.println(list);
}
上面的例子中Comparator<Goods> finalComparator = comparatorForPrice.thenComparing(comparatorForName);
就是複合Lambda表達式的體現。其中thenComparing()方法是Comparator接口的一個默認實現方法。
謂詞複合
謂詞複合,即使用謂詞函接口來實現,謂詞接口定義如下:
@FunctionalInterface
public interface Predicate<T> {
// 抽象接口,判斷是否爲真
boolean test(T t);
// 默認方法,跟另一個謂詞一起判斷
default Predicate<T> and(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) && other.test(t);
}
// 默認方法,判斷後進行非操作
default Predicate<T> negate() {
return (t) -> !test(t);
}
// 默認方法,跟另一個謂詞一起判斷
default Predicate<T> or(Predicate<? super T> other) {
Objects.requireNonNull(other);
return (t) -> test(t) || other.test(t);
}
static <T> Predicate<T> isEqual(Object targetRef) {
return (null == targetRef)
? Objects::isNull
: object -> targetRef.equals(object);
}
}
下面來看下具體的例子:
package learn.java8.ch4;
import java.util.function.Predicate;
public class PredicateTest2 {
static class Goods {
private String name;
// 價格
private int price;
// 庫存
private int storeCount;
public Goods(String name, int price, int storeCount) {
super();
this.name = name;
this.price = price;
this.storeCount = storeCount;
}
}
public static void main(String[] args) {
Goods mete30pro = new Goods("mete30 pro", 4999, 111);
Goods iphone11 = new Goods("iphone11", 5000, 444);
Predicate<Goods> predicate = (goods) -> goods.price > 4000;
System.out.println("mete30pro價格是否大於4000:" + predicate.test(mete30pro));
Predicate<Goods> predicatePrice = (goods) -> goods.price > 6000;
Predicate<Goods> predicateStore = (goods) -> goods.storeCount > 400;
// 價格大於6000或庫存大於400
Predicate<Goods> predicateOr = predicatePrice.or(predicateStore);
System.out.println("價格大於6000或庫存大於400:" + predicateOr.test(iphone11));
}
}
函數複合
函數複合使用java.util.function.Function
函數式接口中來實現。
Function接口定義如下:
// 兩個泛型參數,T表示入參類型,R表示返回類型
@FunctionalInterface
public interface Function<T, R> {
// 抽象方法
R apply(T t);
// 默認實現方法,先執行before,將結果帶入當前apply方法中執行
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
// 按順序執行,先執行當前apply函數,再執行指定的after.apply函數
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
// 輔助方法,始終返回入參值
static <T> Function<T, T> identity() {
return t -> t;
}
}
從代碼上看很容易就能看懂,接下來列舉幾個簡單例子,首先來看下andThen方法的使用:
private static void test1() {
Function<Integer, Integer> funMultiply = (input) -> input * 2;
Function<Integer, Integer> funMinus = (input) -> input - 1;
// input * 2 - 1
Function<Integer, Integer> finalFun = funMultiply.andThen(funMinus);
Integer result = finalFun.apply(2);
System.out.println(result); // 3
}
這個例子中定義兩個函數,一個對參數做乘法操作然後返回,一個對參數做減法操作然後返回。接着使用andThen方法把兩個函數串聯起來。用數學公式表示即爲:2 * 2 - 1
接下來是compose例子:
private static void test2() {
Function<Integer, Integer> funMultiply = (input) -> input * 2;
Function<Integer, Integer> funMinus = (input) -> input - 1;
// (input - 1) * 2
Function<Integer, Integer> finalFun = funMultiply.compose(funMinus);
Integer result = finalFun.apply(2);
System.out.println(result); // 2
}
這裏是先執行減法,得到的結果傳入,再執行乘法操作。用數學公式表示即爲:(2 - 1) * 2
歡迎關注作者微信公衆號:猿敲月下碼,第一時間獲得技術分享