一塊兒來學Java8(四)——複合Lambda

一塊兒來學Java8(二)——Lambda表達式中咱們學習了Lambda表達式的基本用法,如今來了解下複合Lambda。java

Lambda表達式的的書寫離不開函數式接口,複合Lambda的意思是在使用Lambda表達式實現函數式接口抽象方法後,還能夠再次調用接口的其它方法,由於從Java8開始,接口中能夠包含默認實現的方法。關於接口默認實現方法將會在後面章節詳細闡述。app

常見的複合Lambda常見的有如下幾類:iphone

  • 比較器複合,對應的函數式接口:Comparator
  • 謂詞複合,對應的函數式接口:Predicate
  • 函數複合,對應的函數式接口:Function

比較器複合

先來看下Comparator接口的常見用法,針對商品價格從低到高排序ide

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接口的一個默認實現方法。學習

謂詞複合

謂詞複合,即便用謂詞函接口來實現,謂詞接口定義以下:ui

@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);
    }
}

下面來看下具體的例子:this

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函數式接口中來實現。code

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

按期分享技術乾貨,一塊兒學習,一塊兒進步!

相關文章
相關標籤/搜索