文章内容收拾自 博学谷狂野架构

开启生长之旅!这是我参与「日新计划 2 月更文应战」的第 7 天,点击查看活动详情

概述

什么是函数式接口?简略来说便是只有一个笼统函数的接口。为了使得函数式接口的界说愈加规范,java8 供给了@FunctionalInterface 注解告知编译器在编译器去查看函数式接口的合法性,以便在编译器在编译犯错时给出提示。为了愈加规范界说函数接口,给出如下函数式接口界说规则:

  • 有且仅有一个笼统函数
  • 有必要要有@FunctionalInterface 注解
  • 能够有默许办法

能够看出函数式接口的编写界说十分简略,不知道大家有没有注意到,其实我们经常会用到函数式接口,如Runnable 接口,它便是一个函数式接口:

COPY@FunctionalInterface
public interface Runnable {
    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see     java.lang.Thread#run()
     */
    public abstract void run();
}

曩昔我们会运用匿名内部类来完成线程的履行体:

COPYnew Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Hello FunctionalInterface");
            }
        }).start();

现在我们运用Lambda 表达式,这儿函数式接口的运用没有体现函数式编程思维,这儿输出字符到规范输出流中,产生了副效果,起到了简化代码的效果,当然还有装B。

COPYnew Thread(()->{
           System.out.println("Hello FunctionalInterface");
       }).start();

Java8 util.function 包下自带了43个函数式接口,大体分为以下几类:

  • Consumer 消费接口
  • Function 功用接口
  • Operator 操作接口
  • Predicate 断语接口
  • Supplier 生产接口

其他接口都是在此根底上变形定制化罢了。

函数式接口详细介绍

这儿只介绍最根底的函数式接口,至于它的变体只需明白了根底天然就能够明白

Consumer

顾客接口,便是用来消费数据的。

COPY@FunctionalInterface
public interface Consumer<T> {
    /**
     * Performs this operation on the given argument.
     *
     * @param t the input argument
     */
    void accept(T t);
    /**
     * Returns a composed {@code Consumer} that performs, in sequence, this
     * operation followed by the {@code after} operation. If performing either
     * operation throws an exception, it is relayed to the caller of the
     * composed operation.  If performing this operation throws an exception,
     * the {@code after} operation will not be performed.
     *
     * @param after the operation to perform after this operation
     * @return a composed {@code Consumer} that performs in sequence this
     * operation followed by the {@code after} operation
     * @throws NullPointerException if {@code after} is null
     */
    default Consumer<T> andThen(Consumer<? super T> after) {
        Objects.requireNonNull(after);
        return (T t) -> { accept(t); after.accept(t); };
    }
}

Consumer 接口中有accept 笼统办法,accept承受一个变量,也便是说你在运用这个函数式接口的时候,给你供给了数据,你只需接纳运用就能够了;andThen 是一个默许办法,承受一个Consumer 类型,当你对一个数据运用一次还不行爽的时候,你还能再运用一次,当然你其实能够爽无数次,只需一向运用andThan办法。

Function

何为Function呢?比如电视机,给你带来精神上的愉悦,可是它需要用电啊,电视它把电转化成了你荷尔蒙,这便是Function,简略电说,Function 供给一种转化功用。

COPY@FunctionalInterface
public interface Function<T, R> {
    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);
    /**
     * Returns a composed function that first applies the {@code before}
     * function to its input, and then applies this function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of input to the {@code before} function, and to the
     *           composed function
     * @param before the function to apply before this function is applied
     * @return a composed function that first applies the {@code before}
     * function and then applies this function
     * @throws NullPointerException if before is null
     *
     * @see #andThen(Function)
     */
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
        Objects.requireNonNull(before);
        return (V v) -> apply(before.apply(v));
    }
    /**
     * Returns a composed function that first applies this function to
     * its input, and then applies the {@code after} function to the result.
     * If evaluation of either function throws an exception, it is relayed to
     * the caller of the composed function.
     *
     * @param <V> the type of output of the {@code after} function, and of the
     *           composed function
     * @param after the function to apply after this function is applied
     * @return a composed function that first applies this function and then
     * applies the {@code after} function
     * @throws NullPointerException if after is null
     *
     * @see #compose(Function)
     */
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t) -> after.apply(apply(t));
    }
    /**
     * Returns a function that always returns its input argument.
     *
     * @param <T> the type of the input and output objects to the function
     * @return a function that always returns its input argument
     */
    static <T> Function<T, T> identity() {
        return t -> t;
    }
}

Function 接口 最主要的便是apply 函数,apply 承受T类型数据并回来R类型数据,便是将T类型的数据转化成R类型的数据,它还供给了compose、andThen、identity 三个默许办法,compose 承受一个Function,andThen也同样承受一个Function,这儿的andThen 与Consumer 的andThen 类似,在apply之后在apply一遍,compose 则与之相反,在apply之前先apply(这两个apply详细处理内容一般是不同的),identity 起到了类似海关的效果,外国人想要运货进来,总得交点税吧,然后货物才能安全进入中国市场,当然了想不想收税仍是你说了算的。

Operator

能够简略了解成算术中的各种运算操作,当然不仅仅是运算这么简略,由于它只界说了运算这个界说,但至于运算成什么样你说了算。由于没有最根底的Operator,这儿将通过 BinaryOperator、IntBinaryOperator来了解Operator 函数式接口,先从简略的IntBinaryOperator开始。

IntBinaryOperator

从姓名能够知道,这是一个二元操作,而且是Int 类型的二元操作,那么这个接口能够做什么呢,除了加减乘除,还能够能够完成平方(两个相同int 数操作起来不便是平方吗),仍是先看看它的界说吧:

@FunctionalInterface
public interface IntBinaryOperator {
    /**
     * Applies this operator to the given operands.
     *
     * @param left the first operand
     * @param right the second operand
     * @return the operator result
     */
    int applyAsInt(int left, int right);
}

IntBinaryOperator 接口内只有一个applyAsInt 办法,其接纳两个int 类型的参数,并回来一个int 类型的成果,其实这个跟Function 接口的apply 有点像,可是这儿限定了,只能是int类型。

BinaryOperator

BinaryOperator 二元操作,看起来它和IntBinaryOperator 是父子联系,实际上这两者没有半点联系,但他们在功用上仍是有相似之处的:

COPY@FunctionalInterface
public interface BinaryOperator<T> extends BiFunction<T,T,T> {
    /**
     * Returns a {@link BinaryOperator} which returns the lesser of two elements
     * according to the specified {@code Comparator}.
     *
     * @param <T> the type of the input arguments of the comparator
     * @param comparator a {@code Comparator} for comparing the two values
     * @return a {@code BinaryOperator} which returns the lesser of its operands,
     *         according to the supplied {@code Comparator}
     * @throws NullPointerException if the argument is null
     */
    public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) <= 0 ? a : b;
    }
    /**
     * Returns a {@link BinaryOperator} which returns the greater of two elements
     * according to the specified {@code Comparator}.
     *
     * @param <T> the type of the input arguments of the comparator
     * @param comparator a {@code Comparator} for comparing the two values
     * @return a {@code BinaryOperator} which returns the greater of its operands,
     *         according to the supplied {@code Comparator}
     * @throws NullPointerException if the argument is null
     */
    public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) {
        Objects.requireNonNull(comparator);
        return (a, b) -> comparator.compare(a, b) >= 0 ? a : b;
    }
}

BinaryOperator 是 BiFunction 生的,而IntBinaryOperator 是从石头里蹦出来的,BinaryOperator 本身界说了minBy、maxBy默许办法,而且参数都是Comparator,便是依据传入的比较器的比较规则找出最小最大的数据。

Predicate

断语、判别,对输入的数据依据某种规范进行评判,最终回来boolean值:

COPY@FunctionalInterface
public interface Predicate<T> {
    /**
     * Evaluates this predicate on the given argument.
     *
     * @param t the input argument
     * @return {@code true} if the input argument matches the predicate,
     * otherwise {@code false}
     */
    boolean test(T t);
    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * AND of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code false}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ANDed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * AND of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> and(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) && other.test(t);
    }
    /**
     * Returns a predicate that represents the logical negation of this
     * predicate.
     *
     * @return a predicate that represents the logical negation of this
     * predicate
     */
    default Predicate<T> negate() {
        return (t) -> !test(t);
    }
    /**
     * Returns a composed predicate that represents a short-circuiting logical
     * OR of this predicate and another.  When evaluating the composed
     * predicate, if this predicate is {@code true}, then the {@code other}
     * predicate is not evaluated.
     *
     * <p>Any exceptions thrown during evaluation of either predicate are relayed
     * to the caller; if evaluation of this predicate throws an exception, the
     * {@code other} predicate will not be evaluated.
     *
     * @param other a predicate that will be logically-ORed with this
     *              predicate
     * @return a composed predicate that represents the short-circuiting logical
     * OR of this predicate and the {@code other} predicate
     * @throws NullPointerException if other is null
     */
    default Predicate<T> or(Predicate<? super T> other) {
        Objects.requireNonNull(other);
        return (t) -> test(t) || other.test(t);
    }
    /**
     * Returns a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}.
     *
     * @param <T> the type of arguments to the predicate
     * @param targetRef the object reference with which to compare for equality,
     *               which may be {@code null}
     * @return a predicate that tests if two arguments are equal according
     * to {@link Objects#equals(Object, Object)}
     */
    static <T> Predicate<T> isEqual(Object targetRef) {
        return (null == targetRef)
                ? Objects::isNull
                : object -> targetRef.equals(object);
    }
}

Predicate的test 接纳T类型的数据,回来 boolean 类型,即对数据进行某种规则的评判,假如契合则回来true,否则回来false;Predicate接口还供给了 and、negate、or,与 取反 或等,isEqual 判别两个参数是否相等等默许函数。

Supplier

生产、供给数据:

COPY@FunctionalInterface
public interface Supplier<T> {
    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

十分easy,get办法回来一个T类数据,能够供给重复的数据,或许随机种子都能够,就这么简略。

函数式接口实战

Consumer

Consumer 用的太多了,不想说太多,如下:

COPYpublic class Main {
    public static void main(String[] args) {
      Stream.of(1,2,3,4,5,6)
                .forEach(integer -> System.out.println(integer)); //输出1,2,3,4,5,6
    }
}

这儿运用规范输出,仍是产生了副效果,可是这种程度是能够允许的

Function

转化,将字符串转生长度

COPYpublic class Main {
    public static void main(String[] args) {
       Stream.of("hello","FunctionalInterface")
                .map(e->e.length())
                .forEach(System.out::println);
    }
}

运算

COPYpublic class FunctionTest {
    public static void main(String[] args) {
         public static void main(String[] args) {
        Function<Integer, Integer> square = integer -> integer * integer; //界说平方运算
        List<Integer> list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.stream()
                .map(square.andThen(square)) //四次方
                .forEach(System.out::println);
        System.out.println("------");
        list.stream()
                .map(square.compose(e -> e - 1)) //减再三平方
                .forEach(System.out::println);
        System.out.println("------");
        list.stream().map(square.andThen(square.compose(e->e/2))) //先平方然后除2再平方
                .forEach(System.out::println);
    }
}

成果如下

COPY1
16
81
256
------
0
1
4
9
------
0
4
16
64

Operator

BinaryOperator

这儿完成找最大值:

COPYpublic class BinaryOperatorTest {
    public static void main(String[] args) {
        Stream.of(2,4,5,6,7,1)
                .reduce(BinaryOperator.maxBy(Comparator.comparingInt(Integer::intValue))).ifPresent(System.out::println);
    }
}
IntOperator

这儿完成累加功用:

COPYpublic class BinaryOperatorTest {
    public static void main(String[] args) {
        IntBinaryOperator intBinaryOperator = (e1, e2)->e1+e2; //界说求和二元操作
        IntStream.of(2,4,5,6,7,1)
                .reduce(intBinaryOperator).ifPresent(System.out::println);
    }
}

Predicate

筛选出大于0最小的两个数

COPYpublic class Main {
    public static void main(String[] args) {
        IntStream.of(200,45,89,10,-200,78,94)
                .filter(e->e>0) //过滤小于0的数
                .sorted() //天然次序排序
                .limit(2) //取前两个
                .forEach(System.out::println);
    }
}

Supplier

这儿一向生产2这个数字,为了能停下来,运用limit

COPYpublic class Main {
    public static void main(String[] args) {
        Stream.generate(()->2)
                .limit(10)
                .forEach(System.out::println);
    }
}

输出成果

COPY2
2
2
2
2
2
2
2
2
2

总结

Java8的Stream 基本上都是运用util.function包下的函数式接口来完成函数式编程的,而函数式接口也就只分为 Function、Operator、Consumer、Predicate、Supplier 这五大类,只需能了解把握最根底的五大类用法,其他变种也能触类旁通。

本文由传智教育博学谷狂野架构师教研团队发布。

假如本文对您有协助,欢迎重视点赞;假如您有任何建议也可留言评论私信,您的支撑是我坚持创作的动力。

转载请注明出处!