Java之函數式接口@FunctionalInterface詳解(附源碼)


Java之函數式接口@FunctionalInterface詳解

函數式接口的定義

在java8中,滿足下面任意一個條件的接口都是函數式接口:
1、被@FunctionalInterface注釋的接口,滿足@FunctionalInterface注釋的約束。
2、沒有被@FunctionalInterface注釋的接口,但是滿足@FunctionalInterface注釋的約束
@FunctionalInterface注釋的約束:
1、接口有且只能有個一個抽象方法,只有方法定義,沒有方法體
2、在接口中覆寫Object類中的public方法,不算是函數式接口的方法。

比如:

@FunctionalInterface
interface FunctionalInterfaceTest {
    String getInfo(String input);
}

函數式接口的實例

  1. lambda表達式
  2. 方法的引用
  3. 已有構造器或方法的引用
public class Main {

    public static void main(String[] args)
            throws ClassNotFoundException,
            IllegalAccessException,
            InstantiationException,
            NoSuchMethodException,
            InvocationTargetException, NoSuchFieldException {
        /**
         * 1、lambda表達式
         * 這種形式最為直觀,lambda表達式,接收一個String類型的參數,返回一個String類型的結果。
         * 完全符合函數式接口FunctionInterfaceTest的定義
         */
        FunctionalInterfaceTest fiTest1 = str -> str + " copy";
        /**
         * 2、Main方法當中的functionalInterfaceTestMethod方法接收一個參數,返回一個結果。符合函數式接口
         * FunctionInterfaceTest的定義。
         * 函數式接口只是定義了個方法的約定(接收一個String類型的參數,返回一個String類型的結果),
         * 而對於方法內部進行何種操作則並沒有做任何的限制。在這點上,跟java以前的版本中的實現類與接口之間的
         * 關系很類似。不同的是,函數式接口更偏重於計算過程,約束了一個計算過程的輸入和輸出。
         */
        FunctionalInterfaceTest fiTest2 = Main::functionalInterfaceTestMethod;
        /**
         * 3、構造方法引用
         * 構造函數的結構:接收輸入參數,然后返回一個對象。這種約束跟函數式接口的約束很像。
         * 所以只要“輸入參數類型”與“輸出參數類型”跟FunctionInterfaceTest中的方法約束相同,
         * 就可以創建出FunctionInterfaceTest接口的實例,如下,String的構造方法中有
         * new String(str)的構造方法,所以可以得到實例。
         * 這里存在一個類型推斷的問題,JDK的編譯器已經幫我們自動找到了只有一個參數,且是String類型的構造方法。
         * 這就是我們直接String::new,沒有指定使用哪一個構造方法,卻可以創建實例的原因
         */
        FunctionalInterfaceTest fiTest3 = String::new;

        System.out.println(useFunctionalInterface("Hello World!", fiTest1));
        System.out.println(useFunctionalInterface("Hello World!", fiTest2));
        System.out.println(useFunctionalInterface("Hello World!", fiTest3));
        System.out.println(useFunctionalInterface("Hello World!", str -> str + " created by lambda in the context"));
        /**
        輸出:
        		Hello World! copy
						Hello World! copy 2 by reference
            Hello World!
						Hello World! created by lambda in the context
        */
    }
    
  	public static String functionalInterfaceTestMethod(String str) {
        return str + " copy 2 by reference";
    }

    public static String useFunctionalInterface(String str, FunctionalInterfaceTest fiT) {
        return fiT.getInfo(str);
    }
}

常用的封裝好的函數式接口

分別為Function<T, R>, Cosumer<T>, Predicate<T>, Supplier<T>

/**
 * 常用的函數式接口主要有四種類型,是通過其輸入和輸出的參數來進行區分的。定義了編碼過程中主要的使用場景。
 Function<T,R>
 接收一個T類型的參數,返回一個R類型的結果

 Consumer<T>
 接收一個T類型的參數,不返回值

 Predicate<T>
 接收一個T類型的參數,返回一個boolean類型的結果

 Supplier<T>
 不接受參數,返回一個T類型的結果
 */
Function<String, String> add_postfix = str -> str + "postfix";
Consumer<String> print_string = System.out::println;
Predicate<Integer> judge_positive = n -> n > 0;
Supplier<String> supplier = () -> "supply";
List<String> list = Arrays.asList("adfsg", "sdafef", "", "s", "231243", "hgjrepjrg");
list.stream()
        .map(str -> str + "1")
        .filter(str -> str.length() > 2)
        .sorted((str1, str2) -> str2.compareTo(str1))
        .forEach(System.out::println);
/**
	輸出:
			sdafef1
			hgjrepjrg1
			adfsg1
			2312431
			1234dfgh
*/

此外,對於多參數的情況,Java還封裝了BiFunction<T, U, R>, BiConsumer<T, U>, BiPredicate<T, U>。

// 由於java不能返回多個參數,所以沒有BiSupplier
        BiFunction<String, String, String> combine_string = (str1, str2) -> str1 + str2;
        BiConsumer<String, String> print_two_string = (str1, str2) -> System.out.println(str1 + str2);
        BiPredicate<String, String> str_equal = String::equals;
        int bif_result = biFunctionTestMethod("abs", "pdf", (str1, str2) -> str1.length() + str2.length());
        biConsumerTestMethod("1234", "dfgh", (str1, str2) -> System.out.println(str1 + str2));
        boolean bip_result_1 = biPredictTestMethod("abc", "abc", str_equal),
                bip_result_2 = biPredictTestMethod("abc", "def", str_equal);
        System.out.println(bif_result);
        System.out.println(bip_result_1);
        System.out.println(bip_result_2);
/*
		輸出:
				6
				true
				false
*/

在此之外,還有compose和andThen方法,其本質就是數學當中的符合函數,唯一的區別:對於函數\(f(x),g(x)\),compose等價於\(f(g(x))\),andThen等價於\(g(f(x))\),就是執行順序不同而已。

// compose 和 andThen
Function<String, String> compose_function = ((Function<String, String>) (str -> str + "abc")).compose((Function<String, String>) (str -> str + str.length()));
System.out.println("Compose function: " + compose_function.apply("Hello World! "));
Function<String, String> andThen_function = ((Function<String, String>) (str -> str + "abc")).andThen((Function<String, String>) (str -> str + str.length()));
System.out.println("AndThen function: " + andThen_function.apply("Hello World! "));
// Bicosumer, cosumer, bifunction 都有類似功能

// BiPredicate, Predicate 的 and, or, negate
System.out.println(str_equal.negate().test("a", "a")); // false
System.out.println(judge_positive.and(n -> n > 2).test(5)); // true
System.out.println(judge_positive.or(n -> n < -1).test(-10)); // true

源碼

Function.java

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Function<T, R> {

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }

    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }

    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Consumer.java

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Consumer<T> {

    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);

    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Predicate.java

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Predicate<T> {

    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }

    /**
     * Returns a predicate that is the negation of the supplied predicate.
     * This is accomplished by returning result of the calling
     * {@code target.negate()}.
     *
     * @param <T>     the type of arguments to the specified predicate
     * @param target  predicate to negate
     *
     * @return a predicate that negates the results of the supplied
     *         predicate
     *
     * @throws NullPointerException if target is null
     *
     * @since 11
     */
    @SuppressWarnings("unchecked")
    static <T> Predicate<T> not(Predicate<? super T> target) {
        Objects.requireNonNull(target);
        return (Predicate<T>)target.negate();
    }
}

Supplier.java

/**
 * Represents a supplier of results.
 *
 * <p>There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #get()}.
 *
 * @param <T> the type of results supplied by this supplier
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM