溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何使用java函數(shù)式接口

發(fā)布時(shí)間:2021-06-09 09:45:50 來(lái)源:億速云 閱讀:146 作者:小新 欄目:開(kāi)發(fā)技術(shù)

這篇文章主要介紹了如何使用java函數(shù)式接口,具有一定借鑒價(jià)值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

一、函數(shù)式接口的由來(lái)

我們知道使用Lambda表達(dá)式的前提是需要有函數(shù)式接口,而Lambda表達(dá)式使用時(shí)不關(guān)心接口名,抽象方法名。只關(guān)心抽象方法的參數(shù)列表和返回值類型。因此為了讓我們使用Lambda表達(dá)式更加的方法,在JDK中提供了大量常用的函數(shù)式接口

package com.bobo.jdk.fun;

public class Demo01Fun {

    public static void main(String[] args) {
        fun1((arr)->{
            int sum = 0 ;
            for (int i : arr) {
                sum += i;
            }
            return sum;
        });
    }

    public static void fun1(Operator operator){
        int[] arr = {1,2,3,4};
        int sum = operator.getSum(arr);
        System.out.println("sum = " + sum);
    }
}

/**
 * 函數(shù)式接口
 */
@FunctionalInterface
interface Operator{

    int getSum(int[] arr);
}

二、函數(shù)式接口介紹

在JDK中幫我們提供的有函數(shù)式接口,主要是在 java.util.function 包中。

2.1 Supplier

無(wú)參有返回值的接口,對(duì)于的Lambda表達(dá)式需要提供一個(gè)返回?cái)?shù)據(jù)的類型。

@FunctionalInterface
public interface Supplier<T> {

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

使用:

/**
 * Supplier 函數(shù)式接口的使用
 */
public class SupplierTest {

    public static void main(String[] args) {
        fun1(()->{
            int arr[] = {22,33,55,66,44,99,10};
            // 計(jì)算出數(shù)組中的最大值
            Arrays.sort(arr);
            return arr[arr.length-1];
        });
    }

    private static void fun1(Supplier<Integer> supplier){
        // get() 是一個(gè)無(wú)參的有返回值的 抽象方法
        Integer max = supplier.get();
        System.out.println("max = " + max);

    }
}

2.2 Consumer

有參無(wú)返回值得接口,前面介紹的Supplier接口是用來(lái)生產(chǎn)數(shù)據(jù)的,而Consumer接口是用來(lái)消費(fèi)數(shù)據(jù)的,使用的時(shí)候需要指定一個(gè)泛型來(lái)定義參數(shù)類型

@FunctionalInterface
public interface Consumer<T> {

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

使用:將輸入的數(shù)據(jù)統(tǒng)一轉(zhuǎn)換為小寫輸出

public class ConsumerTest {

    public static void main(String[] args) {
        test(msg -> {
            System.out.println(msg + "-> 轉(zhuǎn)換為小寫:" + msg.toLowerCase());
        });
    }

    public static void test(Consumer<String> consumer){
        consumer.accept("Hello World");
    }
}

默認(rèn)方法:andThen

如果一個(gè)方法的參數(shù)和返回值全部是Consumer類型,那么就可以實(shí)現(xiàn)效果,消費(fèi)一個(gè)數(shù)據(jù)的時(shí)候,首先做一個(gè)操作,然后再做一個(gè)操作,實(shí)現(xiàn)組合,而這個(gè)方法就是Consumer接口中的default方法 andThen方法

 default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }

具體的操作

public class ConsumerAndThenTest {

    public static void main(String[] args) {
        test2(msg1->{
            System.out.println(msg1 + "-> 轉(zhuǎn)換為小寫:" + msg1.toLowerCase());
        },msg2->{
            System.out.println(msg2 + "-> 轉(zhuǎn)換為大寫:" + msg2.toUpperCase());
        });
    }


    public static void test2(Consumer<String> c1,Consumer<String> c2){
        String str = "Hello World";
        //c1.accept(str); // 轉(zhuǎn)小寫
        //c2.accept(str); // 轉(zhuǎn)大寫
        //c1.andThen(c2).accept(str);
        c2.andThen(c1).accept(str);
    }
}

2.3 Function

有參有返回值的接口,F(xiàn)unction接口是根據(jù)一個(gè)類型的數(shù)據(jù)得到另一個(gè)類型的數(shù)據(jù),前者稱為前置條件,后者稱為后置條件。有參數(shù)有返回值。

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

使用:傳遞進(jìn)入一個(gè)字符串返回一個(gè)數(shù)字

public class FunctionTest {

    public static void main(String[] args) {
        test(msg ->{
            return Integer.parseInt(msg);
        });
    }

    public static void test(Function<String,Integer> function){
        Integer apply = function.apply("666");
        System.out.println("apply = " + apply);
    }
}

默認(rèn)方法:andThen,也是用來(lái)進(jìn)行組合操作,

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
public class FunctionAndThenTest {

    public static void main(String[] args) {
        test(msg ->{
            return Integer.parseInt(msg);
        },msg2->{
            return msg2 * 10;
        });
    }

    public static void test(Function<String,Integer> f1,Function<Integer,Integer> f2){
        /*Integer i1 = f1.apply("666");
        Integer i2 = f2.apply(i1);*/
        Integer i2 = f1.andThen(f2).apply("666");
        System.out.println("i2:" + i2);

    }
}

默認(rèn)的compose方法的作用順序和andThen方法剛好相反

而靜態(tài)方法identity則是,輸入什么參數(shù)就返回什么參數(shù)

2.4 Predicate

有參且返回值為Boolean的接口

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

使用:

public class PredicateTest {

    public static void main(String[] args) {
        test(msg -> {
            return msg.length() > 3;
        },"HelloWorld");
    }

    private static void test(Predicate<String> predicate,String msg){
        boolean b = predicate.test(msg);
        System.out.println("b:" + b);
    }
}

在Predicate中的默認(rèn)方法提供了邏輯關(guān)系操作 and or negate isEquals方法

package com.bobo.jdk.fun;

import java.util.function.Predicate;

public class PredicateDefaultTest {

    public static void main(String[] args) {
        test(msg1 -> {
            return msg1.contains("H");
        },msg2 -> {
            return msg2.contains("W");
        });
    }

    private static void test(Predicate<String> p1,Predicate<String> p2){
        /*boolean b1 = predicate.test(msg);
        boolean b2 = predicate.test("Hello");*/
        // b1 包含H b2 包含W
        // p1 包含H 同時(shí) p2 包含W
        boolean bb1 = p1.and(p2).test("Hello");
        // p1 包含H 或者 p2 包含W
        boolean bb2 = p1.or(p2).test("Hello");
        // p1 不包含H
        boolean bb3 = p1.negate().test("Hello");
        System.out.println(bb1); // FALSE
        System.out.println(bb2); // TRUE
        System.out.println(bb3); // FALSE
    }
}

感謝你能夠認(rèn)真閱讀完這篇文章,希望小編分享的“如何使用java函數(shù)式接口”這篇文章對(duì)大家有幫助,同時(shí)也希望大家多多支持億速云,關(guān)注億速云行業(yè)資訊頻道,更多相關(guān)知識(shí)等著你來(lái)學(xué)習(xí)!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI