天天看点

Java 8 - 函数式接口

函数式接口定义及应用

只包含一个抽象方法的接口,允许有默认实现方法和静态实现方法的接口称为函数式接口。

可以在函数式接口上使用

@FunctionalInterface

注解,标注它是一个函数式接口,同时javadoc也会包

含一条声明,说明这个接口是一个函数式接口。

如果被

@FunctionalInterface

标注的接口不是一个函数式接口,编译器将返回一个提示原因的错误。

@FunctionalInterface
public interface ICalculator<M, N, R> {
    /**
     * 函数式接口只有一个抽象方法
     */
    R calculate(M m, N n);

    /**
     * 函数式接口可以有实现的默认方法
     */
    default void defaultPrint(R result){
        PrintUtil.println("默认方法输出结果:" + result);
    }

    /**
     * 函数式接口可以有实现的静态方法
     */
    static void staticPrint(String result){
        PrintUtil.println("静态方法输出结果:" + result);
    }
}
           
public class CalculatorDemo {
    public static void main(String[] args) {
        ICalculator<Integer, Integer, Integer> calculator = (x, y) -> x * 10 + y;
        // 执行函数式接口ICalculator的calculate方法
        Integer result = calculator.calculate(1, 2);
        // 执行函数式接口的默认方法
        calculator.defaultPrint(result);
        // 执行函数式接口的静态方法
        ICalculator.staticPrint(result.toString());
    }
}
           

核心函数式接口

函数式接口 参数类型 返回类型 描述
Consumer T void 对类型为T的对象应用操作。
Supplier 返回类型为T的对象。
Function R 对类型为T的对象应用操作,并R类型的返回结果。
Predicate boolean 确定类型为T的对象是否满足约束条件,并返回boolean类型的数据。

Consumer接口

Consumer接口源码

java.util.function.Consumer
@FunctionalInterface
public interface Consumer<T> {
    void accept(T t);
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}
           

Consumer接口用例

public class ConsumerDemo {
    public static void main(String[] args) {
        String product = "产品";
        Consumer<String> consumer1 = str -> PrintUtil.println(str.concat("被消费了"));
        consumer1.accept(product);

        Consumer<String> consumer2 = str -> PrintUtil.print(str.concat("已售空,无法消费"));
        // 先执行对象consumer1的accept方法,在执行consumer2的accept方法
        consumer1.andThen(consumer2).accept(product);
    }
}
           

Supplier接口

Supplier接口源码

java.util.function.Supplier
@FunctionalInterface
public interface Supplier<T> {
    T get();
}
           

Supplier接口用例

public class SupplierDemo {
    public static void main(String[] args) {
        Supplier<Integer> supplier = () -> new Random().nextInt(100);
        PrintUtil.println("生成100以内随机数:" + supplier.get());
    }
}
           

Function接口

Function接口源码

java.util.function.Function
@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;
    }
}
           

Function接口用例

public class FunctionDemo {
    public static void main(String[] args) {
        Function<Integer, String> function = x -> "生成指定范围内的随机数:" + new Random().nextInt(x);
        PrintUtil.println(function.apply(10));  
    }
}
           

Predicate接口

Predicate接口源码

@FunctionalInterface
public interface Predicate<T> {
    boolean test(T t);

    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }

    default Predicate<T> negate() {
        return (t) -> !test(t);
    }

    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }

    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : targetRef::equals;
    }
}
           

Predicate接口用例

原始类型特化函数式接口

函数描述符 原始类型特化
Predicate<T> T->boolean

IntPredicate,

LongPredicate,

DoublePredicate

Consumer<T> T->void

IntConsumer,

LongConsumer,

DoubleConsumer

Function<T,R> T->R

IntFunction<R>,

IntToDoubleFunction,

IntToLongFunction,

LongFunction<R>,

LongToDoubleFunction,

LongToIntFunction,

DoubleFunction<R>,

ToIntFunction<T>,

ToDoubleFunction<T>,

ToLongFunction<T>

Supplier<T> ()->T

BooleanSupplier,

IntSupplier,

LongSupplier,

DoubleSupplier

UnaryOperator<T> T->T

IntUnaryOperator,

LongUnaryOperator,

DoubleUnaryOperator

BinaryOperator<T> (T,T)->T

IntBinaryOperator,

LongBinaryOperator,

DoubleBinaryOperator

BiPredicate<L,R> (L,R)->boolean
BiConsumer<T,U> (T,U)->void

ObjIntConsumer<T>,

ObjLongConsumer<T>,

ObjDoubleConsumer<T>

BiFunction<T,U,R> (T,U)->R

ToIntBiFunction<T,U>,

ToLongBiFunction<T,U>,

ToDoubleBiFunction<T,U>