美文网首页
Java 8 新特性 - 函数式接口 Functional In

Java 8 新特性 - 函数式接口 Functional In

作者: overflowedstack | 来源:发表于2021-06-07 08:03 被阅读0次

    Java8的其中一个新特性,函数式接口。

    • 什么是函数式接口?
      有且仅有一个抽象方法的接口(不包括默认方法、静态方法以及对Object方法的重写)
    • 函数式接口有什么用呢?
      函数式接口不同于以往的普通接口,它最大的作用其实是为了支持行为参数传递,比如传递Lambda、方法引用、函数式接口对应的实例对象等。
    • 函数式接口在什么场景用呢?
      函数中的某一段逻辑(几行code)想要自己定义,其他的部分都是公用的。那么可以将这一段逻辑抽取出来,通过函数式接口,定义不同的逻辑,作为参数传给目标函数。

    1. 传统写法,定义一个接口,定义一个类,实现这个接口

    package com.example.demo.functionalInterface;
    
    interface Task {
        void start();
    }
    
    class TaskImpl implements Task{
    
        @Override
        public void start() {
            System.out.println("Start task");
        }}
    
    public class Test {
        public static void main(String[] args) {        
            Task task = new TaskImpl();
            task.start();
        }
    }
    

    2. 定义一个接口,直接写一个匿名类来实例化

    package com.example.demo.functionalInterface;
    
    interface Task {
        void start();
    }
    
    public class Test {
    
        public static void main(String[] args) {
            Task task = new Task() {
                @Override
                public void start() {
                    System.out.println("Start task!");
                }};
                
            task.start();
        }
    }
    

    3. 用lambda函数来实现

    package com.example.demo.functionalInterface;
    
    interface Task {
        void start();
    }
    
    public class Test {
    
        public static void main(String[] args) {        
            Task task = () -> System.out.println("Start task!");
            task.start();
        }
    }
    

    4. 有返回值的函数,有(多个)参数的函数

    4.1 0参数,有返回值
    package com.example.demo.functionalInterface;
    
    interface Task {
        String start();
    }
    
    public class Test {
    
        public static void main(String[] args) {        
            Task task = () -> "Start task!";
            System.out.println(task.start());
        }
    }
    
    4.2 有一个参数
    package com.example.demo.functionalInterface;
    
    interface Task {
        String start(int id);
    }
    
    public class Test {
    
        public static void main(String[] args) {        
            Task task = (e) -> "Start task " + e;
            System.out.println(task.start(1));
        }
    }
    
    4.3 多个参数
    package com.example.demo.functionalInterface;
    
    interface Task {
        String start(int id, String user);
    }
    
    public class Test {
    
        public static void main(String[] args) {        
            Task task = (e, u) -> "Start task " + e + " by " + u;
            System.out.println(task.start(1, "hanmeimei"));
        }
    }
    

    5. 接口中不能定义多个函数,可用@FunctionalInterface来限定

    若接口中定义多个函数,不能使用lambda函数,会报错。


    多个函数报错

    这时lambda函数会报错,但是接口处并没有报错。可以用注解@FunctionalInterface进行限定。不过这个注解不是必须的,只是让编译器能够报错。


    @FunctionalInterface

    6. Java自带函数式接口, java.util.function里面定义了很多函数式接口,定义了不同的函数,举几个主要的例子

    6.1 Consumer

    Consumer定义了一个accept函数,接收一个参数,无返回值。主要用于只读的场景。
    它还提供了andThen方法,可以串行地执行多个consumer。
    Consumer定义:

    **
     * 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:consumer的用法

    package com.example.demo.functionalInterface;
    
    import java.util.function.Consumer;
    
    public class Test {
        public static void main(String[] args) {        
            testConsumer("myName", t -> {
                if (t.length() >3)
                    System.out.println("The name is " + t);
                else
                    System.out.println("Unexpected name!");
            });
            testConsumer("China", t -> System.out.println("The country is " + t));
        }
        
        private static void testConsumer(String str, Consumer<String> con) {
            System.out.println("Doing something");
            con.accept(str);
            System.out.println("Doing other things");
        }
    }
    

    示例2: consumer andthen的用法

    package com.example.demo.functionalInterface;
    
    import java.util.function.Consumer;
    
    public class Test {
        public static void main(String[] args) {        
            testConsumer("myName", t -> System.out.println("The name is " + t), t -> System.out.println("Complete!"));
            
            testConsumer("China", t -> System.out.println("The country is " + t), t -> System.out.println("Done!"));
        }
        
        private static void testConsumer(String str, Consumer<String> con1, Consumer<String> con2) {
            System.out.println("Doing something");
            con1.andThen(con2).accept(str);
            System.out.println("Doing other things");
        }
    }
    
    6.2 Supplier

    Supplier定义了一个get函数,不接收参数,提供一个返回值。
    Supplier定义:

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

    Supplier用法示例:

    package com.example.demo.functionalInterface;
    
    import java.util.function.Supplier;
    
    public class Test {
        public static void main(String[] args) {        
            testSupplier(() -> "Test!");
            
            testSupplier(() -> "Test again!");
        }
        
        private static void testSupplier(Supplier<String> sup) {
            System.out.println("Doing something");
            System.out.println(sup.get());
            System.out.println("Doing other things");
        }
    }
    
    6.3 Predicate

    Predicate提供了一个test方法,接收一个参数,并返回boolean。

    另外,它还提供了一些操作方法,例如and,or,negate.

    Predicate定义:

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

    Supplier用法示例:
    package com.example.demo.functionalInterface;

    import java.util.Arrays;
    import java.util.function.Predicate;

    public class Test {
    public static void main(String[] args) {
    testPredicate(e -> {
    if (Arrays.asList("Monday", "Tuesday").contains(e)) {
    return true;
    }
    return false;
    });

    }
    
    private static void testPredicate(Predicate<String> sup) {
        System.out.println("Doing something");
        if (sup.test("Monday")) {
            System.out.println("It is a work day!");
        }
        System.out.println("Doing other things");
    }
    

    }

    Supplier or:

        private static void testPredicate(Predicate<String> pre1, Predicate<String> pre2) {
            System.out.println("Doing something");
            if (pre1.or(pre2).test("Saturday")) {
                System.out.println("It is a work day!");
            }
            System.out.println("Doing other things");
        }
    

    negate取反:

        private static void testPredicate(Predicate<String> pre1, Predicate<String> pre2) {
            System.out.println("Doing something");
            if (pre1.negate().test("Saturday")) {
                System.out.println("It is a work day!");
            }
            System.out.println("Doing other things");
        }
    
    6.4 Function

    Function接口提供了apply函数,接收某一个类型的参数,返回另一个类型的结果。
    Function定义:

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

    Function用法示例:

    public class Test {
        public static void main(String[] args) {        
            testPredicate(e -> {
                if ("Monday".equals(e))
                    return 1;
                return 0;
            });
            
        }
        
        private static void testPredicate(Function<String, Integer> function) {
            System.out.println("Doing something");
            System.out.println(function.apply("Monday"));
            System.out.println("Doing other things");
        }
    }
    

    7. 自定义函数接口

    定义一个函数式接口,类似于Function,抛出异常。

    @FunctionalInterface
    protected interface Function<ParamType, ResultType> {
      public ResultType apply(ParamType param) throws Exception;
    }
    

    定义一个函数,其中一个参数为上面接口的实现

    public Response handleMsg(String msg, Function<Context, Response> resFunction) {
      ...
      Context context = new Context(msg);
      ...
      Response response = resFunction.apply(context);
      ...
    }
    

    调用处,传一个lambda函数过去:

    public UpdateResponse handleUpdateMsg(String msg) {
      return handleMsg(msg, (ctx) -> {
        UpdateResponse updateRes = new UpdateResponse();
        updateRes.setValue(handleUpdateMsg(ctx));
        return updateRes;
      });
    }
    

    相关文章

      网友评论

          本文标题:Java 8 新特性 - 函数式接口 Functional In

          本文链接:https://www.haomeiwen.com/subject/zzfesltx.html