函数式接口

作者:xcbeyond
疯狂源自梦想,技术成就辉煌!微信公众号:《程序猿技术大咖》号主,专注后端开发多年,拥有丰富的研发经验,乐于技术输出、分享,现阶段从事微服务架构项目的研发工作,涉及架构设计、技术选型、业务研发等工作。对于Java、微服务、数据库、Docker有深入了解,并有大量的调优经验。












一、函数式接口
函数式接口(functional Interface),有且仅有一个抽象方法的接口,但可以有多个非抽象的方法。

适用于Lambda表达式使用的接口。如创建线程:

new Thread(() -> System.out.println(Thread.currentThread().getName())).start();
1
其中,Lambda表达式代替了new Runnable(),这里的Runable接口就属于函数式接口,最直观的体现是使用了
@FunctionalInterface注解,而且使用了一个抽象方法(有且仅有一个),如下:

package java.lang;

/**
 * The <code>Runnable</code> interface should be implemented by any
 * class whose instances are intended to be executed by a thread. The
 * class must define a method of no arguments called <code>run</code>.
 * <p>
 * This interface is designed to provide a common protocol for objects that
 * wish to execute code while they are active. For example,
 * <code>Runnable</code> is implemented by class <code>Thread</code>.
 * Being active simply means that a thread has been started and has not
 * yet been stopped.
 * <p>
 * In addition, <code>Runnable</code> provides the means for a class to be
 * active while not subclassing <code>Thread</code>. A class that implements
 * <code>Runnable</code> can run without subclassing <code>Thread</code>
 * by instantiating a <code>Thread</code> instance and passing itself in
 * as the target.  In most cases, the <code>Runnable</code> interface should
 * be used if you are only planning to override the <code>run()</code>
 * method and no other <code>Thread</code> methods.
 * This is important because classes should not be subclassed
 * unless the programmer intends on modifying or enhancing the fundamental
 * behavior of the class.
 *
 * @author  Arthur van Hoff
 * @see     java.lang.Thread
 * @see     java.util.concurrent.Callable
 * @since   JDK1.0
 */
@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();
}

1. 格式
修饰符 interface 接口名 {
​ public abstract 返回值类型 方法名 (可选参数列表);

}

注:public abstract可以省略(因为默认修饰为public abstract)

如:

public interface MyFunctionalInterface {
    public abstract void method();
}

2. 注解@FunctionalInterface
@FunctionalInterface,是JDK1.8中新引入的一个注解,专门指代函数式接口,用于一个接口的定义上。

和@Override注解的作用类似,@FunctionalInterface注解可以用来检测接口是否是函数式接口。如果是函数式接口,则编译成功,否则编译失败(接口中没有抽象方法或者抽象方法的个数多余1个)。

package com.xcbeyond.study.jdk8.functional;

/**
 * 函数式接口
 * @Auther: xcbeyond
 * @Date: 2020/5/17 0017 0:26
 */
@FunctionalInterface
public interface MyFunctionalInterface {
    public abstract void method();

    // 如果存在多个抽象方法,则编译失败,即:@FunctionalInterface飘红
//    public abstract void method1();
}

3. 实例
函数式接口:

package com.xcbeyond.study.jdk8.functional;

/**
 * 函数式接口
 * @Auther: xcbeyond
 * @Date: 2020/5/17 0017 0:26
 */
@FunctionalInterface
public interface MyFunctionalInterface {
    public abstract void method();

    // 如果存在多个抽象方法,则编译失败,即:@FunctionalInterface飘红
//    public abstract void method1();
}

测试:

package com.xcbeyond.study.jdk8.functional;

/**
 * 测试函数式接口
 * @Auther: xcbeyond
 * @Date: 2020/5/17 0017 0:47
 */
public class MyFunctionalInterfaceTest {

    public static void main(String[] args) {
        // 调用show方法,参数中有函数式接口MyFunctionalInterface,所以可以使用Lambda表达式,来完成接口的实现
        show("hello xcbeyond!", msg -> System.out.printf(msg));
    }

    /**
     * 定义一个方法,参数使用函数式接口MyFunctionalInterface
     * @param myFunctionalInterface
     */
    public static void show(String message, MyFunctionalInterface myFunctionalInterface) {
        myFunctionalInterface.method(message);
    }
}

函数式接口,用起来是不是更加的灵活,可以在具体调用处进行接口的实现。

函数式接口,可以很友好地支持Lambda表达式。

二、常用的函数式接口
在JDK1.8之前已经有了大量的函数式接口,最熟悉的就是java.lang.Runnable接口了。

JDK 1.8 之前已有的函数式接口:

java.lang.Runnable
java.util.concurrent.Callable
java.security.PrivilegedAction
java.util.Comparator
java.io.FileFilter
java.nio.file.PathMatcher
java.lang.reflect.InvocationHandler
java.beans.PropertyChangeListener
java.awt.event.ActionListener
javax.swing.event.ChangeListener
而在JDK1.8新增了java.util.function包下的很多函数式接口,用来支持Java的函数式编程,从而丰富了Lambda表达式的使用场景。

这里主要介绍四大核心函数式接口:

java.util.function.Consumer:消费型接口
java.util.function.Supplier:供给型接口
java.util.function.Predicate:断定型接口
java.util.function.Function:函数型接口
1. Consumer接口
java.util.function.Consumer接口,是一个消费型的接口,消费数据类型由泛型决定。

package java.util.function;

import java.util.Objects;

/**
 * Represents an operation that accepts a single input argument and returns no
 * result. Unlike most other functional interfaces, {@code Consumer} is expected
 * to operate via side-effects.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #accept(Object)}.
 *
 * @param <T> the type of the input to the operation
 *
 * @since 1.8
 */
@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); };
    }
}

(1)抽象方法:accept
Consumer接口中的抽象方法void accept(T t),用于消费一个指定泛型T的数据。

举例如下:

/**
 * 测试void accept(T t)
 */
@Test
public void acceptMethodTest() {
    acceptMethod("xcbeyond", message -> {
        // 完成字符串的处理,即:通过Consumer接口的accept方法进行对应数据类型(泛型)的消费
        String reverse = new StringBuffer(message).reverse().toString();
        System.out.printf(reverse);
    });
}

/**
 * 定义一个方法,用于消费message字符串
 * @param message
 * @param consumer
 */
public void acceptMethod(String message, Consumer<String> consumer) {
    consumer.accept(message);
}

(2)方法:andThen
方法andThen,可以用来将多个Consumer接口连接到一起,完成数据消费。

/**
 * 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<T> andThen(Consumer<? super T> after)
 * 输出结果:
 *  XCBEYOND
 *  xcbeyond
 */
@Test
public void andThenMethodTest() {
    andThenMethod("XCbeyond", t -> {
        // 转换为大小输出
        System.out.println(t.toUpperCase());
    }, t -> {
        // 转换为小写输出
        System.out.println(t.toLowerCase());
    });
}

/**
 * 定义一个方法,将两个Consumer接口连接到一起,进行消费
 * @param message
 * @param consumer1
 * @param consumer2
 */
public void andThenMethod(String message, Consumer<String> consumer1, Consumer<String> consumer2) {
    consumer1.andThen(consumer2).accept(message);
}

2. Supplier接口
java.util.function.Supplier接口,是一个供给型接口,即:生产型接口。只包含一个无参方法:T get(),用来获取一个泛型参数指定类型的数据。

package java.util.function;

/**
 * Represents a supplier of results.
 *
 * <p>There is no requirement that a new or distinct result be returned each
 * time the supplier is invoked.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #get()}.
 *
 * @param <T> the type of results supplied by this supplier
 *
 * @since 1.8
 */
@FunctionalInterface
public interface Supplier<T> {

    /**
     * Gets a result.
     *
     * @return a result
     */
    T get();
}

举例如下:

@Test
public void test() {
    String str = getMethod(() -> "hello world!");
    System.out.println(str);
}

public String getMethod(Supplier<String> supplier) {
    return supplier.get();
}

3. Predicate接口
java.util.function.Predicate接口,是一个断定型接口,用于对指定类型的数据进行判断,从而得到一个判断结果(boolean类型的值)。

package java.util.function;

import java.util.Objects;

/**
 * Represents a predicate (boolean-valued function) of one argument.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #test(Object)}.
 *
 * @param <T> the type of the input to the predicate
 *
 * @since 1.8
 */
@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);
    }
}

(1)抽象方法:test
抽象方法boolean test(T 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);

举例如下:

/**
 * 测试boolean test(T t);
 */
@Test
public void testMethodTest() {
    String str = "xcbey0nd";
    boolean result = testMethod(str, s -> s.equals("xcbeyond"));
    System.out.println(result);
}

/**
 * 定义一个方法,用于字符串的判断。
 * @param str
 * @param predicate
 * @return
 */
public boolean testMethod(String str, Predicate predicate) {
    return predicate.test(str);
}

(2)方法:and
方法Predicate<T> and(Predicate<? super T> other),用于将两个Predicate进行逻辑”与“判断。

/**
 * 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);
}

(3)方法:negate
方法Predicate<T> negate(),用于取反判断。

 /**
 * 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);
}

(4)方法:or
方法Predicate<T> or(Predicate<? super T> other),用于两个Predicate的逻辑”或“判断。

/**
 * 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);
}

4. Function接口
java.util.function.Function接口,是一个函数型接口,用来根据一个类型的数据得到另外一个类型的数据。

package java.util.function;

import java.util.Objects;

/**
 * Represents a function that accepts one argument and produces a result.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object)}.
 *
 * @param <T> the type of the input to the function
 * @param <R> the type of the result of the function
 *
 * @since 1.8
 */
@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;
    }
}

(1)抽象方法:apply
抽象方法R apply(T t),根据类型T的参数获取类型R的结果。

/**
 * Applies this function to the given argument.
 *
 * @param t the function argument
 * @return the function result
 */
R apply(T t);

举例如下:

/**
 * 测试R apply(T t),完成字符串整数的转换
 */
@Test
public void applyMethodTest() {
    // 字符串类型的整数
    String numStr = "123456";
    Integer num = applyMethod(numStr, n -> Integer.parseInt(n));
    System.out.println(num);
}

public Integer applyMethod(String str, Function<String, Integer> function) {
    return function.apply(str);
}

(2)方法:compose
方法<V> Function<V, R> compose(Function<? super V, ? extends T> before),获取apply的function。

/**
 * 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));
}

(3)方法:andThen
方法<V> Function<T, V> andThen(Function<? super R, ? extends V> after),用来进行组合操作,即:”先做什么,再做什么“的场景。

 /**
 * 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));
}

三、函数式编程
函数式编程并不是Java提出的新概念,它将计算机运算看作是函数的计算。函数式编程最重要的基础是λ演算,而且λ演算的函数是可以接受函数当作输入(参数)和输出(返回值)的。

和指令式编程相比,函数式编程强调函数的计算比指令的执行重要。

和过程化编程相比,函数式编程里函数的计算可随时调用。

当然,Java大家都知道是面向对象的编程语言,一切都是基于对象的特性(抽象、封装、继承、多态)。在JDK1.8出现之前,我们关注的往往是某一对象应该具有什么样的属性,当然这也就是面向对象的核心——对数据进行抽象。但JDK1.8出现以后,这一点开始出现变化,似乎在某种场景下,更加关注某一类共有的行为(有点类似接口),这也就是JDK1.8提出函数式编程的目的。如下图所示,展示了面向对象编程到函数式编程的变化。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cOkAh3K9-1590250788080)(./4.面向对象编程到函数式编程的变化.png)]

Lambda表达式就是更好的体现了函数式编程,而为了支持Lambda表达式,才有了函数式接口。

另外,为了在面对大型数据集合时,为了能够更加高效的开发,编写的代码更加易于维护,更加容易运行在多核CPU上,java在语言层面增加了Lambda表达式。在上一节中,我们已经知道Lambda表达式是多么的好用了 。

在JDK1.8中,函数式编程随处可见,在你使用过程中简直很爽,例如:Stream流。

函数式编程的优点,也很多,如下:

1. 代码简洁,开发快速
函数式编程大量使用函数,减少了代码的重复,因此程序比较短,开发速度较快。

2. 接近自然语言,易于理解
函数式编程的自由度很高,可以写出很接近自然语言的代码。

例如,两数只差,可以写成(x, y) -> x – y

3. 更方便的代码管理
函数式编程不依赖、也不会改变外界的状态,只要给定输入参数,返回的结果必定相同。因此,每一个函数都可以被看做独立单元,很有利于进行单元测试(unit testing)和除错(debugging),以及模块化组合。

4. 易于"并发编程"
函数式编程不需要考虑"死锁",因为它不修改变量,所以根本不存在"锁"线程的问题。不必担心一个线程的数据,被另一个线程修改,所以可以很放心地把工作分摊到多个线程,部署"并发编程"。

5. 代码的热升级
函数式编程没有副作用,只要保证接口不变,内部实现是外部无关的。所以,可以在运行状态下直接升级代码,不需要重启,也不需要停机。

四、总结
在JDK1.8中,函数式接口/编程将会随处可见,也有有助于你更好的理解JDK1.8中的一些新特性。关于函数式接口,在接下来具体特性、用法中将会体现的淋漓尽致。

JDK1.8提出的函数式接口,你是否赞同呢?

参考资料:

1.https://www.cnblogs.com/Dorae/p/7769868.html

2.https://blog.csdn.net/stormkai/article/details/94364233

3.https://baike.baidu.com/item/函数式编程