jdk1.8的四大函數式接口


一. Functional

public class FunctionDemo {

    public static void main(String[] args) {
        String result = testFuntion("kobe", name -> name + " bryant");
        System.out.println(result);
    }

    /**
     * 函數型接口,有輸入,有輸出
     *
     * @param name
     * @param function
     * @return
     */
    public static String testFuntion(String name, Function<String, String> function) {
        return function.apply(name);
    }

}

二. Consumer

public class ConsumerDemo {

    public static void main(String[] args) {
        testConsumer(2, x -> System.out.println("傳入的數字為:" + x));
    }

    /**
     * 消費型接口,有輸入,但是沒返回值
     * 
     * @param num
     * @param consumer
     * @return
     */
    private static void testConsumer(int num, Consumer<Integer> consumer) {
        consumer.accept(num);
    }

}

三. Supplier

public class SupplierDemo {

    public static void main(String[] args) {
        String result = testSupplier(() -> "hello man!");
        System.out.println(result);
    }

    /**
     * 供給型接口,無輸入,有輸出
     * 
     * @param supplier
     * @return
     */
    public static String testSupplier(Supplier<String> supplier) {
        return supplier.get();
    }

}

四. Predicate

public class PredicateDemo {

    public static void main(String[] args) {
        Boolean flag = testPredicate("b", str -> str.equals("a"));
        System.out.println(flag);
    }

    /**
     * 斷言型接口,有輸出,輸出為Boolean
     *
     * @param str
     * @param predicate
     * @return
     */
    public static Boolean testPredicate(String str, Predicate<String> predicate) {
        return predicate.test(str);
    }

}


免責聲明!

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



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