Java Lambda基础——Function, Consumer, Predicate, Supplier, 及FunctionalInterface接口

这几个接口常常与Lambda结合使用,网上固然也有不少介绍,不过有些过于繁琐,有些又偏简单,秉着实用主义精神,今天这里折中一下,把介绍的内容分为两部分,第一部分至关于TLDR,总结几个“口诀”,便于你们记忆,对于更想看用法示例的同窗们,第二部分者提供了全部这些接口的示例。但愿对你们有所帮助。html

口诀

    如无参数,请使用Supplier(Use Supplier if it takes nothing)java

    如无返回,请使用Consumer(Use Consumer if it returns nothing)程序员

    如二者都无,请使用Runnable(Use Runnable if it does neither)app

    如二者都有,请使用Function(Use Function if it does both)大数据

    如返回布尔值,请使用Predicate(Use Predicate if it returns a boolean)spa

    如以上皆不能够,请使用自定义@FunctionalInteface(Use @FunctionalInteface if none of above works)3d

示例

  1. Supplier
private static <T> testSupplier(Supplier<T> supplier) {
    return supplier.get();
}
...
Integer s = testSupplier(() -> 7 + 3); // 不接受任何参数,但会返回数据
System.out.println(s); // 输出10
  1. Consumer
private static <T> void testConsumer(Consumer<T> consumer, T data) {
    consumer.accept(data);
}
...
testConsumer(System.out::println, "dummy"); // 直接调用println,输出"dummy",无任何返回
  1. Runnable
private static void testRunnable(Runnable runnable) {
    runnable.run();
}
...
testRunnable(() -> System.out.println("dummy")); // 既无输入,也无输出
  1. Function
private static <T, R> testFunction(Function<T, R> function, T data) {
    return function.apply(data);
}
...
Integer f = testFunction((d) -> d * 23); // 既有输入,也有输出(将给定值X2)
System.out.println(f); // 输出6
  1. Predicate
private static <T> boolean testPredicate(Predicate<T> predicate, T data) {
    return predicate.test(data);
}
...
boolean p = testPredicate((d) -> d > 0100); // 接受输入,输出布尔值(判断给定值是否为正数)
System.out.println(p); // 输出true
  1. @FunctionalInterface
@FunctionalInterface
public interface CalculationFuncInterface<TUR{
    public R apply(T l, U i);
}
...
private static <T, U, R> testFunctionalInterface(CalculationFuncInterface<T, U, R> cal, T data1, U data2) {
    return cal.apply(data1, data2);
}
...
Integer fi = testFunctionalInterface((a, b) -> a * b, 67); // 接受两个输入参数,并返回其乘积
System.out.println(fi); // 输出42

今天的介绍就先到这,感谢你们,Cheers!



公众号“程序员杂书馆”,欢迎关注。 免费送出O'Reilly 《Spark快速大数据分析》纸质书(亦有一批PDF分享)!
相关文章
相关标签/搜索