抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

函数式接口

函数式接口:有且只有一个抽象方法的,可以有多个非抽象方法的接口,主要用于 Lambda 表达式

例如:

@FunctionalInterface
public interface Runnable {
public abstract void run();
}
@FunctionalInterface
public interface Function<T, R> {

R apply(T t);


default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}


default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}


static <T> Function<T, T> identity() {
return t -> t;
}
}

@FunctionalInterface :用于检查是否符合函数式接口

Since jdk 1.8 ,java.util.function 包中主要是这四个方法,其他都是四个方法的拓展

/*
* Function 函数型接口:第一个 String 为返回类型,第二个 String 为输入参数类型
* */
public static void FunctionFunction() {
Function<String, String> function = (str) -> {
return str;
};
System.out.println(function.apply("heroxin"));
}
/*
* Predicate 断定型接口,输入参数,返回布尔值
* */
public static void PredicateFunction() {
Predicate<String> predicate = (str) -> {
return str.isEmpty();
};
System.out.println(predicate.test("heroxin"));
}

/*
* Consumer 消费型接口:有输入参数,没有返回值
* */
public static void ConsumerFunction() {
Consumer<String> consumer = (str) -> {
System.out.println(str);
};
consumer.accept("heroxin");
}
/*
* Supplier 供给型接口:没有输入参数,有返回值
* */
public static void SupplierFunction() {
Supplier<String> supplier = () -> {
return "heroxin";
};
System.out.println(supplier.get());
}

评论