天天看點

JDK8函數式接口Function、Consumer、Predicate、Supplier

上文介紹了什麼是函數式接口,本文介紹一些具體的函數式接口。

JDK8函數式接口Function、Consumer、Predicate、Supplier

JDK8以前,通過匿名内部類可以實作接口:

Function<Integer, String> fun = new Function<Integer, String>() {
            @Override
            public String apply(Integer t) {
                return String.valueOf(t);
            }
        };
           

JDK8中,通過lambda表達式實作:

Function<Integer, String> fun = (x) -> String.valueOf(x);
           

可以得出一個結論,lambda表達式就是為了優化匿名内部類而生。

String res = fun.apply(1000);
System.out.println(res); 
           

一、Function功能型函數式接口

Function接口 接受一個輸入參數T,傳回一個結果R。

package java.util.function;
import java.util.Objects;

@FunctionalInterface
public interface Function<T, R> {
    // 接受輸入參數,對輸入執行所需操作後  傳回一個結果。
    R apply(T t);

    // 傳回一個 先執行before函數對象apply方法,再執行目前函數對象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));
    }   

    // 傳回一個執行了apply()方法之後隻會傳回輸入參數的函數對象。
    static <T> Function<T, T> identity() {
        return t -> t;
    } 
}
           

例:apply方法使用:

public class FunctionDemo {

    static int modifyTheValue(int valueToBeOperated, Function<Integer, Integer> function) {
        return function.apply(valueToBeOperated);
    }

    public static void main(String[] args) {
        int myNumber = 10;

        // 使用lambda表達式實作函數式接口
        // (x)->(x)+20 輸入一個參數x,進行加法運算,傳回一個結果
        // 是以該lambda表達式可以實作Function接口
        int res1 = modifyTheValue(myNumber, (x)-> x + 20);
        System.out.println(res1); // 30

        //  使用匿名内部類實作
        int res2 = modifyTheValue(myNumber, new Function<Integer, Integer>() {
            @Override
            public Integer apply(Integer t) {
                return t + 20;
            }
        });
        System.out.println(res2); // 30
    }
}
           

例:andThen方法使用

public static Integer modifyTheValue2(int value, Function<Integer, Integer> function1, Function<Integer, Integer> function2){
         //value作為function1的參數,傳回一個結果,該結果作為function2的參數,傳回一個最終結果
         return  function1.andThen(function2).apply(value);
    }

    public static void main(String[] args) {
        System.out.println(modifyTheValue2(3, val -> val + 2, val -> val + 3));
    }
           

二、Consumer消費型函數式接口

代表了 接受一個輸入參數并且無傳回的操作

例:accept方法使用

public static void modifyTheValue3(int value, Consumer<Integer> consumer) {
        consumer.accept(value);
    }

    public static void main(String[] args) {
        // (x) -> System.out.println(x * 2)接受一個輸入參數x
        // 直接輸出,并沒有傳回結果
        // 是以該lambda表達式可以實作Consumer接口
        modifyTheValue3(3, (x) -> System.out.println(x * 2));
    }
           

輸出:6

三、Predicate斷言型函數式接口

接受一個輸入參數,傳回一個布爾值結果。

例:test方法使用1

public static boolean predicateTest(int value, Predicate<Integer> predicate) {
        return predicate.test(value);
    }

    public static void main(String[] args) {
        // (x) -> x == 3 輸入一個參數x,進行比較操作,傳回一個布爾值
        // 是以該lambda表達式可以實作Predicate接口
        System.out.println(predicateTest(3, (x) -> x == 3));
    }
           

輸出:true

例:test方法使用2

public static void eval(List<Integer> list, Predicate<Integer> predicate) {
        for (Integer n : list) {
            if (predicate.test(n)) {
                System.out.print(n + " ");
            }
        }

//      list.forEach(n -> {
//          if (predicate.test(n)) {
//              System.out.print(n + " ");
//          }
//      });
    }

    public static void main(String args[]) {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

        // Predicate<Integer> predicate = n -> true
        // n 是一個參數傳遞到 Predicate 接口的 test 方法
        // n 如果存在則 test 方法傳回 true

        System.out.println("輸出所有資料:");

        // 傳遞參數 n
        eval(list, n -> true);

        // Predicate<Integer> predicate1 = n -> n%2 == 0
        // n 是一個參數傳遞到 Predicate 接口的 test 方法
        // 如果 n%2 為 0 test 方法傳回 true

        System.out.println("\n輸出所有偶數:");
        eval(list, n -> n % 2 == 0);

        // Predicate<Integer> predicate2 = n -> n > 3
        // n 是一個參數傳遞到 Predicate 接口的 test 方法
        // 如果 n 大于 3 test 方法傳回 true

        System.out.println("\n輸出大于 3 的所有數字:");
        eval(list, n -> n > 3);
    }
           

輸出:

輸出所有資料:1 2 3 4 5 6 7 8 9 輸出所有偶數:2 4 6 8 輸出大于 3 的所有數字:4 5 6 7 8 9 
           

例:test方法使用3

public static boolean validInput(String name, Predicate<String> function) {  
        return function.test(name);  
    }  

    public static void main(String args[]) {
        String name = "冷冷";
        if(validInput(name, s -> !s.isEmpty() &&  s.length() <= 3 )) {
            System.out.println("名字輸入正确");
        }
    }
           

三、Supplier供給型函數式接口

無參數,傳回一個結果。

例:get方法使用

public static String supplierTest(Supplier<String> supplier) {  
        return supplier.get();  
    }  

    public static void main(String args[]) {
        String name = "冷冷";
        // () -> name.length() 無參數,傳回一個結果(字元串長度)
        // 是以該lambda表達式可以實作Supplier接口
        System.out.println(supplierTest(() -> name.length() + ""));
    }