原创

java函数式接口

温馨提示:
本文最后更新于 2023年05月11日,已超过 340 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

函数式接口

只包含一个抽象方法的接口,称为函数式接口。

这个接口可以使用@FunctionalInterface声明,如果不满足条件,则会报错,可以通过这个方式来判断是否为函数式接口

file

package org.example;

@FunctionalInterface
public interface MathService {
    Double add(double a, double b);
}

可以有额外的defualt关键字方法:

package org.example;

@FunctionalInterface
public interface MathService {
    Double add(double a, double b);
    default void test(){
        System.out.println("test");
    }
}

可以有额外的Object的public方法:

package org.example;

@FunctionalInterface
public interface MathService {
    Double add(double a, double b);
    default void test(){
        System.out.println("test");
    }
    /**
     * Object的equals方法
     * @param obj
     * @return
     */
    @Override
    boolean equals(Object obj);

    /**
     * Object的toString方法
     * @return
     */
    @Override
    String toString();

    /**
     * Object的hashCode方法
     * @return
     */
    @Override
    int hashCode();
}

java的四大函数式接口

Consumer接口

顾名思义,消费式接口,没有返回值,可以接收一个参数进行处理,java的定义如下:

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

除去一个accept方法之后,额外有一个andThen方法,可以实现多次循环调用

    public static void main(String[] args) throws Exception {
        Consumer<String> c1 = (String s) -> {
            System.out.println("c1 consumer:"+s);
        };
        Consumer<String> c2 = (String s) -> {
            System.out.println("c2 consumer:"+s);
        };
        c1.andThen(c2).accept("111");
    }

Supplier接口

Supplier是供给型接口,调用后将有返回值,接口定义如下:

@FunctionalInterface
public interface Supplier<T> {

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

可以看出,这个接口跟consumer是可以组合使用的,一个是生产数据,一个是消费数据

    public static void main(String[] args) throws Exception {
        Supplier<String> s = () -> {
            //获取当前的字符串时间
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df.format(new Date());
        };

        Consumer<String> c = time -> {
            System.out.println("consumer:" + time);
        };
        for (int i = 0; i < 10; i++) {
            c.accept(s.get());
            TimeUnit.SECONDS.sleep(1);
        }
    }

Function接口

Function接口是函数型接口,有返回值,Java8中对Function接口的定义如下:

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

函数型接口的作用为,通过传入一个参数来获得一个新的参数(输入,输出).

    public static void main(String[] args) throws Exception {
        //将string转换为int
        Function<String,Integer> function1 = (String s) -> Integer.parseInt(s);

        //将int转换为int*2
        Function<Integer,Integer> function2 = (Integer i) -> i*2;

        Function<Integer,Integer> function3 = (Integer i) -> i-2;

        //组合两个函数,先执行function3,再执行function2
        Function<Integer,Integer> function4 = function2.compose(function3);
        //组合两个函数,先执行function1,再执行function2
        Function<Integer,Integer> function5 = function2.andThen(function3);

        //执行function1,将string转换为int
        Integer result = function1.apply("1");
        System.out.println(result);
        //执行function4,将string转换为int,再将int*2
        Integer result2 = function4.apply(2);
        System.out.println(result2);
        //执行function5,将string转换为int,再将int*2
        Integer result3 = function5.apply(2);
        System.out.println(result3);
    }

Predicate接口

断言型接口,传入一个参数,返回一个bool值,一般用于单元测试,java接口定义:

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

使用示例:

    public static void main(String[] args) throws Exception {
        //判断传入的值是否等于1,如果不等于则false
        Predicate predicate = (x) -> x.equals("1");
        System.out.println(predicate.test("2"));
        System.out.println(predicate.test("1"));

    }

Predicate额外提供了多个default方法,用法如下:

    public static void main(String[] args) throws Exception {
        //判断传入的值是否等于1,如果不等于则false
        Predicate predicate = (x) -> x.equals("1");
        //判断传入的值是否为字符串
        Predicate predicate1 = (x) -> x instanceof String;
        //判断传入的值是否为字符串,并且判断是否等于1
        Predicate predicate2 = predicate.and(predicate1);
        System.out.println(predicate2.test("1"));
        //判断传入的值是否为字符串,或者判断是否等于1
        Predicate predicate3 = predicate.or(predicate1);
        System.out.println(predicate3.test("1"));
        //判断是否不等于1
        Predicate predicate4 = predicate.negate();
        System.out.println(predicate4.test("1"));
    }
正文到此结束
本文目录