• Java8新特性04 内置功能接口


    内置功能接口借鉴了Google Guava库的实践。Java8的内置功能接口在java.util.function包下,主要有四大核心的功能性接口:谓词(predicate)、函数(function)、生产者(supplier)、消费者(consumer)

    一. 谓词(Predicate)

    这里是谓词的源码:

      1 /*
      2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
      3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
      4  *
      5  *
      6  *
      7  *
      8  *
      9  *
     10  *
     11  *
     12  *
     13  *
     14  *
     15  *
     16  *
     17  *
     18  *
     19  *
     20  *
     21  *
     22  *
     23  *
     24  */
     25 package java.util.function;
     26 
     27 import java.util.Objects;
     28 
     29 /**
     30  * Represents a predicate (boolean-valued function) of one argument.
     31  *
     32  * <p>This is a <a href="package-summary.html">functional interface</a>
     33  * whose functional method is {@link #test(Object)}.
     34  *
     35  * @param <T> the type of the input to the predicate
     36  *
     37  * @since 1.8
     38  */
     39 @FunctionalInterface
     40 public interface Predicate<T> {
     41 
     42     /**
     43      * Evaluates this predicate on the given argument.
     44      *
     45      * @param t the input argument
     46      * @return {@code true} if the input argument matches the predicate,
     47      * otherwise {@code false}
     48      */
     49     boolean test(T t);
     50 
     51     /**
     52      * Returns a composed predicate that represents a short-circuiting logical
     53      * AND of this predicate and another.  When evaluating the composed
     54      * predicate, if this predicate is {@code false}, then the {@code other}
     55      * predicate is not evaluated.
     56      *
     57      * <p>Any exceptions thrown during evaluation of either predicate are relayed
     58      * to the caller; if evaluation of this predicate throws an exception, the
     59      * {@code other} predicate will not be evaluated.
     60      *
     61      * @param other a predicate that will be logically-ANDed with this
     62      *              predicate
     63      * @return a composed predicate that represents the short-circuiting logical
     64      * AND of this predicate and the {@code other} predicate
     65      * @throws NullPointerException if other is null
     66      */
     67     default Predicate<T> and(Predicate<? super T> other) {
     68         Objects.requireNonNull(other);
     69         return (t) -> test(t) && other.test(t);
     70     }
     71 
     72     /**
     73      * Returns a predicate that represents the logical negation of this
     74      * predicate.
     75      *
     76      * @return a predicate that represents the logical negation of this
     77      * predicate
     78      */
     79     default Predicate<T> negate() {
     80         return (t) -> !test(t);
     81     }
     82 
     83     /**
     84      * Returns a composed predicate that represents a short-circuiting logical
     85      * OR of this predicate and another.  When evaluating the composed
     86      * predicate, if this predicate is {@code true}, then the {@code other}
     87      * predicate is not evaluated.
     88      *
     89      * <p>Any exceptions thrown during evaluation of either predicate are relayed
     90      * to the caller; if evaluation of this predicate throws an exception, the
     91      * {@code other} predicate will not be evaluated.
     92      *
     93      * @param other a predicate that will be logically-ORed with this
     94      *              predicate
     95      * @return a composed predicate that represents the short-circuiting logical
     96      * OR of this predicate and the {@code other} predicate
     97      * @throws NullPointerException if other is null
     98      */
     99     default Predicate<T> or(Predicate<? super T> other) {
    100         Objects.requireNonNull(other);
    101         return (t) -> test(t) || other.test(t);
    102     }
    103 
    104     /**
    105      * Returns a predicate that tests if two arguments are equal according
    106      * to {@link Objects#equals(Object, Object)}.
    107      *
    108      * @param <T> the type of arguments to the predicate
    109      * @param targetRef the object reference with which to compare for equality,
    110      *               which may be {@code null}
    111      * @return a predicate that tests if two arguments are equal according
    112      * to {@link Objects#equals(Object, Object)}
    113      */
    114     static <T> Predicate<T> isEqual(Object targetRef) {
    115         return (null == targetRef)
    116                 ? Objects::isNull
    117                 : object -> targetRef.equals(object);
    118     }
    119 }
    View Code

    说明:谓词是单参数的返回布尔值的函数式接口,输入一个函数,返回true或者false。同时该接口也包含多个默认方法或静态方法使用谓词转换成复杂的逻辑表达式(与、或、非等)

    举例

     1 package com.test.a;
     2 
     3 import java.util.function.Predicate;
     4 
     5 public class Test {
     6     public static void main(String args[]) {
     7         
     8        String str="hello";
     9        
    10        //1.测试抽象方法
    11        Predicate<String> predicate1=(String s)->s.length()>6;
    12        boolean result1=predicate1.test(str);
    13        System.out.println(result1);//false
    14        
    15        //2.使用 default Predicate<T> and(Predicate<? super T> other)
    16        Predicate<String> predicate2=(String s)->s.length()==5;
    17        boolean result2=predicate1.and(predicate2).test(str);
    18        System.out.println(result2);//false
    19        
    20        //3.使用 default Predicate<T> or(Predicate<? super T> other) 
    21        boolean result3=predicate1.or(predicate2).test(str);
    22        System.out.println(result3);//true
    23        
    24        //4.使用default Predicate<T> negate()
    25        boolean result4=predicate1.negate().test(str);
    26        System.out.println(result4);//true
    27        
    28        //5.使用static <T> Predicate<T> isEqual(Object targetRef)
    29        Predicate<String> predicate5=Predicate.isEqual("hello2");
    30        boolean result5=predicate5.test(str);
    31        System.out.println(result5);//false
    32  
    33     }
    34 }
    View Code

    二. 函数(Function)

    这是函数的源码:

      1 /*
      2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
      3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
      4  *
      5  *
      6  *
      7  *
      8  *
      9  *
     10  *
     11  *
     12  *
     13  *
     14  *
     15  *
     16  *
     17  *
     18  *
     19  *
     20  *
     21  *
     22  *
     23  *
     24  */
     25 package java.util.function;
     26 
     27 import java.util.Objects;
     28 
     29 /**
     30  * Represents a function that accepts one argument and produces a result.
     31  *
     32  * <p>This is a <a href="package-summary.html">functional interface</a>
     33  * whose functional method is {@link #apply(Object)}.
     34  *
     35  * @param <T> the type of the input to the function
     36  * @param <R> the type of the result of the function
     37  *
     38  * @since 1.8
     39  */
     40 @FunctionalInterface
     41 public interface Function<T, R> {
     42 
     43     /**
     44      * Applies this function to the given argument.
     45      *
     46      * @param t the function argument
     47      * @return the function result
     48      */
     49     R apply(T t);
     50 
     51     /**
     52      * Returns a composed function that first applies the {@code before}
     53      * function to its input, and then applies this function to the result.
     54      * If evaluation of either function throws an exception, it is relayed to
     55      * the caller of the composed function.
     56      *
     57      * @param <V> the type of input to the {@code before} function, and to the
     58      *           composed function
     59      * @param before the function to apply before this function is applied
     60      * @return a composed function that first applies the {@code before}
     61      * function and then applies this function
     62      * @throws NullPointerException if before is null
     63      *
     64      * @see #andThen(Function)
     65      */
     66     default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
     67         Objects.requireNonNull(before);
     68         return (V v) -> apply(before.apply(v));
     69     }
     70 
     71     /**
     72      * Returns a composed function that first applies this function to
     73      * its input, and then applies the {@code after} function to the result.
     74      * If evaluation of either function throws an exception, it is relayed to
     75      * the caller of the composed function.
     76      *
     77      * @param <V> the type of output of the {@code after} function, and of the
     78      *           composed function
     79      * @param after the function to apply after this function is applied
     80      * @return a composed function that first applies this function and then
     81      * applies the {@code after} function
     82      * @throws NullPointerException if after is null
     83      *
     84      * @see #compose(Function)
     85      */
     86     default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
     87         Objects.requireNonNull(after);
     88         return (T t) -> after.apply(apply(t));
     89     }
     90 
     91     /**
     92      * Returns a function that always returns its input argument.
     93      *
     94      * @param <T> the type of the input and output objects to the function
     95      * @return a function that always returns its input argument
     96      */
     97     static <T> Function<T, T> identity() {
     98         return t -> t;
     99     }
    100 }
    View Code

    说明:Function接受一个参数,并产生一个结果。默认方法可以将多个函数串在一起(compose,andThen)

    default <V> Function<V, R> compose(Function<? super V, ? extends T> before)返回一个先执行before函数对象apply方法,再执行当前函数对象apply方法的函数对象;

    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after)返回一个先执行当前函数对象apply方法,再执行after函数对象apply方法的函数对象;

    举例

     1 package com.test.a;
     2 
     3 import java.util.function.Function;
     4 
     5 public class Test {
     6     public static void main(String args[]) {
     7   
     8         String str="hello";
     9         Function<String, Integer> function=(String)->2;
    10         Integer result=function.apply(str);
    11         System.out.println(result);
    12         
    13         Function<Integer, Integer> function2=(Integer i )->i*2;
    14         Function<Integer, Integer> function3=(Integer j )->j*j;
    15         int result2=function2.compose(function3).apply(2);//先算function3的结果,再算function2的结果
    16         System.out.println(result2);
    17         int result3=function2.andThen(function3).apply(2);//先算function2的结果,再算function3的结果
    18         System.out.println(result3);
    19         
    20     
    21     }
    22 }
    View Code
    1 2
    2 8
    3 16
    View Code

     三. 生产者(Supplier)

    这是生产者的源码:

     1 /*
     2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     4  *
     5  *
     6  *
     7  *
     8  *
     9  *
    10  *
    11  *
    12  *
    13  *
    14  *
    15  *
    16  *
    17  *
    18  *
    19  *
    20  *
    21  *
    22  *
    23  *
    24  */
    25 package java.util.function;
    26 
    27 /**
    28  * Represents a supplier of results.
    29  *
    30  * <p>There is no requirement that a new or distinct result be returned each
    31  * time the supplier is invoked.
    32  *
    33  * <p>This is a <a href="package-summary.html">functional interface</a>
    34  * whose functional method is {@link #get()}.
    35  *
    36  * @param <T> the type of results supplied by this supplier
    37  *
    38  * @since 1.8
    39  */
    40 @FunctionalInterface
    41 public interface Supplier<T> {
    42 
    43     /**
    44      * Gets a result.
    45      *
    46      * @return a result
    47      */
    48     T get();
    49 }
    View Code

    说明:Suppliers产生一个给定的泛型类型的结果。与Function不同的是Suppliers不接受输入参数。

    举例

     1 import java.util.function.Supplier;
     2 
     3 public class Test {
     4     public static void main(String args[]) {
     5   
     6         Supplier<String> supplier=()->"hello";
     7         System.out.println(supplier.get());
     8     
     9     }
    10 }
    11 
    12 
    13 hello
    14 
    15 note:上面的String可以改成具体的对象,比如person对象,从而调用对象的set和get方法等操作
    View Code

    四. 消费者(Consumer)

    这是消费者的源码:

     1 /*
     2  * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
     4  *
     5  *
     6  *
     7  *
     8  *
     9  *
    10  *
    11  *
    12  *
    13  *
    14  *
    15  *
    16  *
    17  *
    18  *
    19  *
    20  *
    21  *
    22  *
    23  *
    24  */
    25 package java.util.function;
    26 
    27 import java.util.Objects;
    28 
    29 /**
    30  * Represents an operation that accepts a single input argument and returns no
    31  * result. Unlike most other functional interfaces, {@code Consumer} is expected
    32  * to operate via side-effects.
    33  *
    34  * <p>This is a <a href="package-summary.html">functional interface</a>
    35  * whose functional method is {@link #accept(Object)}.
    36  *
    37  * @param <T> the type of the input to the operation
    38  *
    39  * @since 1.8
    40  */
    41 @FunctionalInterface
    42 public interface Consumer<T> {
    43 
    44     /**
    45      * Performs this operation on the given argument.
    46      *
    47      * @param t the input argument
    48      */
    49     void accept(T t);
    50 
    51     /**
    52      * Returns a composed {@code Consumer} that performs, in sequence, this
    53      * operation followed by the {@code after} operation. If performing either
    54      * operation throws an exception, it is relayed to the caller of the
    55      * composed operation.  If performing this operation throws an exception,
    56      * the {@code after} operation will not be performed.
    57      *
    58      * @param after the operation to perform after this operation
    59      * @return a composed {@code Consumer} that performs in sequence this
    60      * operation followed by the {@code after} operation
    61      * @throws NullPointerException if {@code after} is null
    62      */
    63     default Consumer<T> andThen(Consumer<? super T> after) {
    64         Objects.requireNonNull(after);
    65         return (T t) -> { accept(t); after.accept(t); };
    66     }
    67 }
    View Code

    说明:Consumers代表一个单一的输入参数上执行操作。Consumer的操作可能会更改输入参数的内部状态。

    举例

     1 package com.test.a;
     2 
     3 import java.util.function.Consumer;
     4 
     5 public class Test {
     6     public static void main(String args[]) {
     7 
     8         Consumer<Person> consumer = (Person person) -> person.setAge(23);
     9         Person person = new Person();
    10         person.setAge(25);
    11         consumer.accept(person);
    12         System.out.println(person.getAge());
    13     }
    14 }
    15 
    16 
    17 23
    View Code
  • 相关阅读:
    perl linux 编译成可执行程序
    MQSeries::Message 面向对象接口的MQSeries messages
    数据化管理第一步,你真的会做报表吗?
    数据化管理第一步,你真的会做报表吗?
    aix ipcs 官方解释
    使用jquery.qrcode生成二维码及常见问题解决方案
    案例分享|某医药集团的BI建设案例
    aix ipcs OxFFFFFFFF
    案例分享|某医药集团的BI建设案例
    地图应用之 :获取当前位置的经纬度
  • 原文地址:https://www.cnblogs.com/Hermioner/p/9662890.html
Copyright © 2020-2023  润新知