函数式接口

1、介绍

在这个接口里只能有一个抽象方法,它们主要应用在Lambda表达式上。

Java 8为函数式接口引入了一个新注解@FunctionalInterface,主要用于编译级错误检查,加上该注解,当你写的接口不符合函数式接口定义的时候,编译器会报错。

例如:定义一个函数式接口

@FunctionalInterface

public class MyFunctionalInterface(){

    void sendMsg(String msg);

}

然后就可以使用Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):

String msgtset = "您有新的消息";

MyFunctionalInterface myFunctionalInterface = msg -> {

    Syste.out.println("消息通知:"+msg);

}

myFunctionalInterface.sendMsg(msgtset);

由此可见,Lambda表达式返回的是一个实例对象

以下介绍的时候Java8新增的四大函数式接口的使用:


Comsumer接口(消费型:有参数无返回值)

(1)源码

@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

注:andThen使用了default关键字来修饰,default是Java8引入的新特性,对于使用default修饰的方法,在编写其接口实现类的时候,无需再重新实现该方法

Objects.requireNonNull(after):

当after对象为null的时候,会立即抛出异常,而不是等到使用到after的时候才抛出NullPointExecption空指针异常

(2)使用案例:

当使用lamda表达式实例化Comsumer类的时候,默认实现的是accept方法,例如

Comsumer<String> con1 = message -> {System.out.println("系统启动成功:"+"message");}

Comsumer<String> con2 = message -> {System.out.println("系统启动失败:"+"message");}

然后就可以通过con对象直接调用上文实现了的accept方法,输出字符串

con1.accept("测试结果");

con2.accept("测试结果");

或者,也可以Consumer类的andThen方法,来顺序调用consumer实例对象

con1.andThen(con2).accept("测试结果");

输出结果:

系统启动成功:测试结果

系统启动失败:测试结果


Suplier接口(供给型:无参数,有返回值)

(1)源码

/**

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

}

该接口仅有一个抽象方法get

(2)使用案例

Random ran = new Random();

Supplier<Integer> sup = () -> {

    ran.nextInt(10);

}

System.out.println(sup.get());

输出结果:[随机数]


Function(函数型:有参数,有返回值)

(1)源码

/**

* 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接口类只有一个抽象方法apply需要实现,同时也有一个类似Comsumer类的andThen方法,但是和Comsumer类相比,Function类还多了一个default方法compose和static方法identify

compose和andThen相反,andThen是先执行调用者,再执行参数;compose是先执行参数,再执行调用者

identify则是返回当前调用的方法

(2)使用案例

    public static void main(String[] args) {

        Function<Integer, Integer> times2 = i -> i*2;

        Function<Integer, Integer> squared = i -> i*i;

        System.out.println(times2.apply(4));  //8

        System.out.println(squared.apply(4));  //16

        //先4×4然后16×2,先执行apply(4),在times2的apply(16),先执行参数,再执行调用者。

        System.out.println(times2.compose(squared).apply(4));  //32


      //先4×2,然后8×8,先执行times2的函数,在执行squared的函数。

      System.out.println(times2.andThen(squared).apply(4));  //64             

      System.out.println(Function.identity().compose(squared).apply(4));  //16

    }


Predicate(断言式,返回值为布尔类型)

(1)源码

/**

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

    }

}

该接口有一个抽象方法test需要实现,该方法传入参数为泛型,返回值只能是boolean类型

另外还有三个default方法:and,or,negate和一个static方法isEqual

and:对两个断言式接口类的实例化对象进行与操作

or:对两个断言式接口类的实例化对象进行或操作

negate:对两个断言式接口类的实例化对象进行非操作

isEqual:返回一个比较目标值是否相等的Predicate实例对象,可以比较null值

(2)使用案例

String s1 = "ABC";

String s2 = null;

System.out.println(Predicate.isEqual(null).test(s2)); //true

System.out.println(Predicate.isEqual("ABC").test(s1)); //true

System.out.println(Predicate.isEqual(s2).test(s1)); //false

System.out.println(Predicate.isEqual(s1).test(s2)); //false

System.out.println(Predicate.isEqual(null).and(Predicate.isEqual("ABC")).test(s2)); //false

System.out.println(Predicate.isEqual(null).or(Predicate.isEqual("ABC")).test(s2)); //true

System.out.println(s2.equals(s1)); //java.lang.NullPointerException

System.out.println(s1.equals(s2)); //false

System.out.println(Predicate.isEqual(null).test(null)); //true

可见,使用Predicate的isEqual方法进行判断的时候,不会出现空指针异常,书写代码时无需考虑空指针错误

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容