函数式接口
函数式接口:有且只有一个抽象方法的,可以有多个非抽象方法的接口,主要用于 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 包中主要是这四个方法,其他都是四个方法的拓展
public static void FunctionFunction() { Function<String, String> function = (str) -> { return str; }; System.out.println(function.apply("heroxin")); }
|
public static void PredicateFunction() { Predicate<String> predicate = (str) -> { return str.isEmpty(); }; System.out.println(predicate.test("heroxin")); }
|
public static void ConsumerFunction() { Consumer<String> consumer = (str) -> { System.out.println(str); }; consumer.accept("heroxin"); }
|
public static void SupplierFunction() { Supplier<String> supplier = () -> { return "heroxin"; }; System.out.println(supplier.get()); }
|