前言
我们知道Lambda表达式应用在函数式接口中,除了我们平时自己写的函数式接口外,源码中的哪些常用接口也可以使用呢?
函数型接口Function<T, R>
源码
* @since 1.8
*/
@FunctionalInterface
public interface Function<T, R>{
R apply(T t);
}
用法:T 是入参,R是出参,结合lamdba表达式一起使用
Function<String, String> fun = e ->"hello:"+e;
fun.apply("freshman"))
消费型接口Consumer
源码
* @since 1.8
*/
@FunctionalInterface
public interface Consumer<T> {
void accept(T t);
}
用法:有入参,没有入参
Consumer<Integer> fun = e ->System.out.println(e/1);;
fun.accept(0);
供给型接口Supplier
源码
* @since 1.8
*/
@FunctionalInterface
public interface Supplier<T> {
T get();
}
用法:没有入参,有出参
Supplier<Object> fn = ()-> new Object();
Object obj = fn.get();
断言型接口Predicate
源码
* @since 1.8
*/
@FunctionalInterface
public interface Predicate<T> {
boolean test(T t);
}
用法:有入参,返回boolen值
Predicate<Integer> fn =(e)->10<e;
fn.test(10);