这几个接口经常与Lambda结合使用,网上当然也有很多介绍,不过有些过于繁琐,有些又偏简单,秉着实用主义精神,今天这里折中一下,把介绍的内容分为两部分,第一部分相当于TLDR,总结几个“口诀”,便于大家记忆,对于更想看用法示例的同学们,第二部分者提供了所有这些接口的示例。希望对大家有所帮助。
口诀
√如无参数,请使用Supplier(Use Supplier if it takes nothing)
√如无返回,请使用Consumer(Use Consumer if it returns nothing)
√如两者都无,请使用Runnable(Use Runnable if it does neither)
√如两者都有,请使用Function(Use Function if it does both)
√如返回布尔值,请使用Predicate(Use Predicate if it returns a boolean)
√如以上皆不可以,请使用自定义@FunctionalInteface(Use @FunctionalInteface if none of above works)
示例
- Supplier
private static <T> T testSupplier(Supplier<T> supplier) {
return supplier.get();
}
...
Integer s = testSupplier(() -> 7 + 3); // 不接受任何参数,但会返回数据
System.out.println(s); // 输出10
- Consumer
private static <T> void testConsumer(Consumer<T> consumer, T data) {
consumer.accept(data);
}
...
testConsumer(System.out::println, "dummy");
