函数式接口


#Java 笔记


从 Java 8 开始支持函数式接口。

函数式接口注解 FunctionalInterface

源码:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface FunctionalInterface {}

说明:

根据源码注释,

  • 该注解只能用于接口,不能用于注解、枚举、类。
  • 被注解的类型,必须满足函数式接口的条件。

函数式接口条件:

  • 只能有一个抽象方法(abstract method)。
  • default 方法因为是有具体实现的,所以不算抽象方法。
  • 抽象方法不能和 java.lang.Object 的方法相同。

函数式接口的实例,可以用于 lambda 表达式、函数引用、构造器引用。

示例

定义函数式接口如下:

@FunctionalInterface
public interface IProcessor<T> {

    void process(T t);

}

Java 8 之前的写法:

public class Main {

    public static void main(String[] args) {
        IProcessor<Long> processor = new IProcessor<Long>() {
            @Override
            public void process(Long aLong) {
                System.out.println(aLong);
            }
        };

        processor.process(123L);
    }

}

使用 Java 8 的 lambda 写法:

public class Main {

    public static void main(String[] args) {
        IProcessor<Long> processor = aLong -> {
            System.out.println(aLong);
        };
        processor.process(123L);
    }

}

使用 lambda + 函数引用:

public class Main {

    public static void main(String[] args) {
        IProcessor<Long> processor = System.out::println;
        processor.process(123L);
    }

}

函数式接口 Runnable:无参数, 无返回值

全路径: java.lang.Runnable

该接口在 Java 8 之前就存在,从 Java 8 开始加了注解 @FunctionalInterface。一般用于多线程开发中。

源码:

@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();
}

代码示例:

public class Main {

    public static void main(String[] args) {
        Runnable runnable = () -> {
            System.out.println("你好");
        };
        runnable.run();  // 输出: 你好
    }

}

函数式接口 Callable:无参数, 有返回值

全路径: java.util.concurrent.Callable 。

该接口在 Java 8 之前就存在,从 Java 8 开始加了注解 @FunctionalInterface。一般用于多线程开发的场景中。

非多线程开发,考虑使用 java.util.function.Supplier ,如果认为语义不合适,考虑自定义。

源码:

@FunctionalInterface
public interface Callable<V> {
    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;
}

注意,这里的 call 方法声明了会抛出异常。使用时,外层函数要catch或者也跟着声明抛出异常。

代码示例:

import java.util.concurrent.Callable;

public class Main {

    public static void main(String[] args) throws Exception {
        Callable<Long> callable = () -> {
            return 100L;
        };
        System.out.println(callable.call());
    }

}

函数式接口 Consumer:1个参数, 无返回值

全路径: java.util.function.Consumer 。

Java 8 中引入。

源码:

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

代码示例:

import java.util.function.Consumer;

public class Main {

    public static void main(String[] args) {
        Consumer<Long> consumer = num -> {
            System.out.println("参数是: " + num);
        };

        consumer.accept(123L);
    }

}

执行结果:

参数是: 123

函数式接口 Supplier:无参数, 有返回值

全路径: java.util.function.Supplier 。

Java 8 中引入。

源码:

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();
}

代码示例:

import java.util.function.Supplier;

public class Main {

    public static void main(String[] args) {
        Supplier<Long> supplier = () -> {
            return System.currentTimeMillis() + 1;
        };

        System.out.println(supplier.get());
    }

}

函数式接口 Function:1个参数, 有返回值

全路径: java.util.function.Function 。

Java 8 中引入。

源码:


/**
 * 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

import java.util.function.Function;

public class Main {

    public static void main(String[] args) {
        Function<Long, String> function = aLong -> {
            return "数字是: " + aLong;
        };

        String result = function.apply(123L);
        System.out.println(result);
    }

}

执行结果:

数字是: 123

代码示例2

import java.util.function.Function;

public class Main {

    public static void main(String[] args) {
        Function<Long, Long> function = aLong -> {
            System.out.println("数字加2");
            return aLong + 2;
        };

        Function<Long, Long> function2 = function.compose(aLong -> {
            System.out.println("数字加10");
            return aLong + 10;
        });

        Function<Long, Long> function3 = function2.andThen(aLong -> {
            System.out.println("数字加100");
            return aLong + 100;
        });

        Long result = function3.apply(123L);
        System.out.println("执行结果: " + result);
    }

}

执行结果:

数字加10
数字加2
数字加100
执行结果: 235

函数式接口 BiFunction:2个参数, 有返回值

全路径: java.util.function.BiFunction 。

Java 8 中引入。

源码:

package java.util.function;

import java.util.Objects;

/**
 * Represents a function that accepts two arguments and produces a result.
 * This is the two-arity specialization of {@link Function}.
 *
 * <p>This is a <a href="package-summary.html">functional interface</a>
 * whose functional method is {@link #apply(Object, Object)}.
 *
 * @param <T> the type of the first argument to the function
 * @param <U> the type of the second argument to the function
 * @param <R> the type of the result of the function
 *
 * @see Function
 * @since 1.8
 */
@FunctionalInterface
public interface BiFunction<T, U, R> {

    /**
     * Applies this function to the given arguments.
     *
     * @param t the first function argument
     * @param u the second function argument
     * @return the function result
     */
    R apply(T t, U u);

    /**
     * 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
     */
    default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
        Objects.requireNonNull(after);
        return (T t, U u) -> after.apply(apply(t, u));
    }
}

代码示例

import java.util.function.BiFunction;

public class Main {

    public static void main(String[] args) {
        BiFunction<Long, Long, Long> add = (num1, num2) -> {
            return num1 + num2;
        };

        Long result = add.apply(1L, 2L);
        System.out.println("执行结果: " + result);
    }

}

执行结果:

执行结果: 3

函数引用

这里给一个示例。

定义函数式接口如下:

@FunctionalInterface
public interface IProcessor<T> {

    void process(T t);

}

使用 lambda:

public class Main {

    public static void main(String[] args) {
        IProcessor<Long> processor = aLong -> {
            System.out.println(aLong);
        };
        processor.process(123L);
    }

}

使用 lambda + 函数引用:

public class Main {

    public static void main(String[] args) {
        IProcessor<Long> processor = System.out::println;
        processor.process(123L);
    }

}


( 本文完 )