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