java8几个重要的函数接口
来源:互联网 发布:方正字体排查软件 编辑:程序博客网 时间:2024/05/22 23:14
1、Function<T, R> 函数接口
2、BiFunction<T, U, R>函数接口
3、UnaryOperator<T>函数接口
3.2、使用方法举例:
4、BinaryOperator<T>函数接口
4.2、使用方法举例:
5、Predicate<T>函数接口
5.2、使用方法举例:
6、Consumer<T>函数接口
6.2、使用方法举例:
7、Supplier<T>函数接口
7.2、使用方法举例:
1.1、源码分析 :
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/23 21:09 * @ProjectName: JavaBaseTest * <></> */import java.util.Objects;/** * 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)}. * 这是一个函数接口,它的函数方法为:apply * * @param <T> the type of the input to the function * @param <R> the type of the result of the function * * @since 1.8 */@FunctionalInterfacepublic 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. * 此方法返回一个组合函数. * 这一函数的执行过程:先对参数执行before函数,然后对结果执行apply函数. * before函数和apply函数,任一函数执行出现异常,则异常会被转到组合函数compose那里. * * ----本函数:体现了前套关系 * * @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. * andThen方法,返回一个组合函数. * andThen方法的执行过程:先对输入参数执行apply函数,然后对结果执行after函数. * apply函数和apply函数,任一函数执行出现异常,则异常会被转到这一组合函数的调用者那里. * * ----本函数:转换了嵌套的顺序 * * @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.2、使用方法举例:
//Function<T, R> import java.util.function.Function;public class Main { public static void main(String[] args) { //Function Function<String,Integer> function1= s -> s.length(); //1.功能方法:apply System.out.println(function1.apply("LiJin")); //2.默认方法:compose Function<Integer,String> function2=integer->String.valueOf(integer); System.out.println(function2.compose(Integer::lowestOneBit).apply(100)); //3.默认方法:andThen Function<Integer,String> function3=i-> { if(i==5) return "LiJin"; else return "LiLy"; }; System.out.println(function3.andThen(String::new).apply(11)); System.out.println(function3.andThen(String::new).apply(5)); //4.静态方法:identity System.out.println(Function.identity().apply(111)); }}//输出54LiLyLiJin111Process finished with exit code 0
2、BiFunction<T, U, R>函数接口
2.1、源码分析:
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/23 21:32 * @ProjectName: JavaBaseTest */import java.util.Objects;/** * Represents a function that accepts two arguments and produces a result. * This is the two-arity specialization of {@link java.util.function.Function}. * 这是一个二元函数,二元函数没有compose能力. * 函数功能:输入两个参数,返回一个结果. * * <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 java.util.function.Function * @since 1.8 */@FunctionalInterfacepublic interface BiFunction<T, U, R> { /** * Applies this function to the given arguments. * 处理2个输入参数的方法:apply * * @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. * * addThen方法:返回一个组合函数. * 函数执行过程:先对输入参数执行apply函数,再对apply的结果执行after函数. * 如果执行过程中,任一函数发生异常,异常会被返回到组合函数的调用者这里. * * @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(java.util.function.Function<? super R, ? extends V> after) { Objects.requireNonNull(after); return (T t, U u) -> after.apply(apply(t, u)); }}
2.2、使用方法举例:
//BiFunction<T, U, R>import java.util.function.BiFunction;public class Main { public static void main(String[] args) { //BiFunction //1.功能方法:apply BiFunction<String,String,Integer> function=(s,t)->s.length()+t.length(); System.out.println(function.apply("cao","xiao")); //2.默认方法:andThen BiFunction<String,String,String> function1=(t,u)->t+u; System.out.println(function1.andThen(String::new).apply("cao","xiao")); }}//输出7caoxiaoProcess finished with exit code 0
3、UnaryOperator<T>函数接口
3.1、源码分析:
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/23 22:03 * @ProjectName: JavaBaseTest *//** * Represents an operation on a single operand that produces a result of the * same type as its operand. This is a specialization of {@code Function} for * the case where the operand and result are of the same type. * 这一函数只有一个参数,且返回结果和输入参数一致. * 这一接口继承于Function接口. * 其功能方法为apply.(这一点由其继承接口决定) * * <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 operand and result of the operator * * @see java.util.function.Function * @since 1.8 */@FunctionalInterfacepublic interface UnaryOperator<T> extends java.util.function.Function<T, T> { /** * Returns a unary operator that always returns its input argument. * * @param <T> the type of the input and output of the operator * @return a unary operator that always returns its input argument */ static <T> UnaryOperator<T> identity() { return t -> t; }}
3.2、使用方法举例:
//UnaryOperator<T>import java.util.function.UnaryOperator;public class Main { public static void main(String[] args) { //UnaryOperator<T> //1.功能函数:apply UnaryOperator<Integer> uOpe=x->x++; System.out.println(uOpe.apply(10)); //2.静态方法:identity() System.out.println(UnaryOperator.identity().apply("abc")); //3.默认方法:compose,这个方法是因为继承接口java.util.function.Function<T, T> 得到的 UnaryOperator<Integer> uOpe2=integer -> integer+=1; System.out.println(uOpe2.compose(Integer::highestOneBit).apply(100)); //4.默认方法:andThen,这个方法是因为继承接口java.util.function.Function<T, T> 得到的 UnaryOperator<Integer> uOpe3=integer -> integer+=2; System.out.println(uOpe3.andThen(Integer::highestOneBit).apply(100)); }}//输出10abc6564Process finished with exit code 0
4、BinaryOperator<T>函数接口
4.1、源码分析:
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/23 21:55 * @ProjectName: JavaBaseTest */import java.util.Comparator;import java.util.Objects;/** * Represents an operation upon two operands of the same type, producing a result * of the same type as the operands. This is a specialization of * {@link java.util.function.BiFunction} for the case where the operands and the result are all of * the same type. * 这一函数对两个类型相同的参数做操作,且返回结果类型和参数相同. * 这一接口继承自BiFunction接口,两个操作数和返回结果类型均相同. * 它的功能方法为apply,因为继承自BiFunction嘛 * * <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 operands and result of the operator * * @see java.util.function.BiFunction * @see UnaryOperator * @since 1.8 */@FunctionalInterfacepublic interface BinaryOperator<T> extends java.util.function.BiFunction<T,T,T> { /** * Returns a {@link BinaryOperator} which returns the lesser of two elements * according to the specified {@code Comparator}. * 根据传如比较器,返回两个比较元素中那个较小的元素. * * @param <T> the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the lesser of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */ public static <T> BinaryOperator<T> minBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator); return (a, b) -> comparator.compare(a, b) <= 0 ? a : b; } /** * Returns a {@link BinaryOperator} which returns the greater of two elements * according to the specified {@code Comparator}. * 根据给定比较器,返回两个比较元素中较大的那个原色. * * @param <T> the type of the input arguments of the comparator * @param comparator a {@code Comparator} for comparing the two values * @return a {@code BinaryOperator} which returns the greater of its operands, * according to the supplied {@code Comparator} * @throws NullPointerException if the argument is null */ public static <T> BinaryOperator<T> maxBy(Comparator<? super T> comparator) { Objects.requireNonNull(comparator); return (a, b) -> comparator.compare(a, b) >= 0 ? a : b; }}
4.2、使用方法举例:
//BinaryOperator<T>import java.util.Comparator;import java.util.function.BinaryOperator;public class Main { public static void main(String[] args) { //BinaryOperator<T> //1.功能方法:apply BinaryOperator<Integer> add=(x,y)->x+y; System.out.println("add : "+add.apply(11,12)); //2.静态方法:minBy(Comparator<? super T> comparator) Comparator<Integer> min=(x,y)->x-y; System.out.println("min : "+BinaryOperator.minBy(min).apply(1,3)); //3.静态方法:maxBy(Comparator<? super T> comparator) Comparator<Integer> max=(x,y)->x-y; System.out.println("max : "+BinaryOperator.maxBy(max).apply(3,1)); }}//输出add : 23min : 1max : 3Process finished with exit code 0
5、Predicate<T>函数接口
5.1、源码分析:
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/23 22:12 * @ProjectName: JavaBaseTest */import java.util.Objects;/** * Represents a predicate (boolean-valued function) of one argument. * * predicate主要是用于推导真价值的. * 使用场景:帮助开发一些返回值为boolean值的函数. * 功能函数为:test方法 * * <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 */@FunctionalInterfacepublic interface Predicate<T> { /** * Evaluates this predicate on the given argument. * 将给定参数和预测做对比,返回一个boolean类型的值. * 如何和预测一致,返回true;否则,返回false. * * @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. * 这一方法,返回组合函数的值,实质是:对两个test值做与操作. * 函数执行过程:先检查传入参数t的test值,如果为false,直接返回false;否则继续 * 继续检查传入参数t是否满足:other条件 * * <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. * 返回这个逻辑否定的谓词. * 使用方式:predicate.negate().test(value) * 如果test值为true,则这个表达式返回false; * 否则,返回true. * * @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. * 这一方法就是求或. * 执行过程:先对参数t求test值,如果为true,则返回; * 否则,检验t是否满足other条件,如果满足,返回true;否则返回false. * * * <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)}. * 如果两个比较参数的内存地址是否相同. * 函数返回结果为:一个谓词 * 使用方式: * Object obj=new Object(); * Object obj2=new Object(); * System.out.println(Predicate.isEqual(obj).test(obj2));//输出:false * @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); }}
5.2、使用方法举例:
//Predicate<T>import java.util.function.Predicate;public class Main { public static void main(String[] args) { //Predicate<T> //1.功能方法:test(T t) Predicate<String> pred1=s -> s.equals("cxh"); System.out.println(pred1.test("cxh")); System.out.println(pred1.test("caoxiao")); //2.默认方法:and(Predicate<? super T> other). // 条件1.and(条件2)的执行顺序:先检测条件1,再检测条件2 Predicate<String> pred2=s -> s.length()>10; Predicate<String> pred3=s->s.equals("lingye1234567"); System.out.println(pred2.and(pred3).test("lingye1234567"));//要求字符串长度>10 && 字符串==lingye1234567 System.out.println(pred2.and(pred1).test("cxh"));//要求字符串长度>10 && 字符串==cxh //3.默认方法:negate() Predicate<Integer> pred4=i->i>10; System.out.println(pred4.test(11)); System.out.println(pred4.negate().test(11)); //4.默认方法:or(Predicate<? super T> other) Predicate<Integer> pred5=i->i>10; Predicate<Integer> pred6=i->i<5; System.out.println(pred5.or(pred6).test(8)); System.out.println(pred5.or(pred6).test(11)); //5.静态方法:isEqual(Object targetRef) Object a=new Object(); Object b=a; Object c=new Object(); System.out.println(Predicate.isEqual(a).test(b)); System.out.println(Predicate.isEqual(a).test(c)); }}//输出:truefalsetruefalsetruefalsefalsetruetruefalseProcess finished with exit code 0
6、Consumer<T>函数接口
6.1、源码分析:
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/23 23:35 * @ProjectName: JavaBaseTest */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. * 本函数接口特点: * (1)输入参数只有一个 * (2)没有返回结果 * * 和其它函数接口的区别:Consumer函数期望通过副作用从而完成操作. * 这一函数接口的功能函数为:accept(T t) * * * <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 */@FunctionalInterfacepublic 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. * * andThen方法,会执行两次Consumer接口的accept方法, * 执行顺序上,先对输入参数执行accept方法;然后再对a输入参数执行after方法.(注意:两次都是对同一个输入参数的操作,而不是第二次是对第一次操作的结果做处理) * 任一方法执行出现异常,则异常会被抛给本函数接口的调用者. * 如果执行accept方法时出现异常,则after方法不会再被继续执行. * * Consumer<Integer> consumer1=x->{System.out.println("consumer is :"+x+1);}; Consumer<Integer> consumer2=x->{System.out.println("con2 is:"+x);}; consumer1.andThen(consumer2).accept(100); * 输出: * consumer is :1001 * con2 is:100 * * * @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); }; }}
6.2、使用方法举例:
//Consumer<T>import java.util.function.Consumer;public class Main { public static void main(String[] args) { //Consumer<T> //1.功能方法:accept(T t) Consumer<Integer> consumer1=x->{ System.out.println(x); }; consumer1.accept(111); //2.默认方法:andThen(Consumer<? super T> after) Consumer<Integer> consumer2=x-> System.out.println(x+1); Consumer<Integer> consumer3=x-> System.out.println(x+2); consumer2.andThen(consumer3).accept(111); }}//输出111112113Process finished with exit code 0
7、Supplier<T>函数接口
7.1、源码分析:
package sourcecode.analysis;/** * @Author: cxh * @CreateTime: 17/12/24 10:31 * @ProjectName: JavaBaseTest *//** * Represents a supplier of results. * 这是一个提供结果的函数接口. * 特点: * (1)只有返回值 * (2)没有输入参数 * <p>There is no requirement that a new or distinct result be returned each * time the supplier is invoked. * * get()方法被调用时,对于一定要new出一个新对象 or 生成一个和之前结果不同的值 这两方面,都没有强制规定. * 这一接口函数的功能方法为:get() * * <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 */@FunctionalInterfacepublic interface Supplier<T> { /** * Gets a result. * * @return a result */ T get();}
7.2、使用方法举例:
//Supplier<T>import java.util.function.Supplier;public class Main { public static void main(String[] args) { //Supplier<T> //1.功能函数:get() Supplier<String> supplier=()->"lingye"; System.out.println(supplier.get()); }}//输出lingyeProcess finished with exit code 0
阅读全文