加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java8几个重要的函数接口

发布时间:2020-12-14 06:39:20 所属栏目:Java 来源:网络整理
导读:span style="font-size:14px;"1、FunctionT,R 函数接口 /** @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. 接受一个参

<span style="font-size:14px;">1、Function<T,R> 函数接口

/**

  • @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.

  • 接受一个参数,并返回一个结果值.

  • This is a

  • whose functional method is {@link #apply(Object)}.

  • 这是一个函数接口,它的函数方法为:apply

  • @param the type of the input to the function

  • @param 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.
    • 此方法返回一个组合函数.
    • 这一函数的执行过程:先对参数执行before函数,然后对结果执行apply函数.
    • before函数和apply函数,任一函数执行出现异常,则异常会被转到组合函数compose那里.
    • ----本函数:体现了前套关系
    • @param 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 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 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 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 the type of the input and output objects to the function
    • @return a function that always returns its input argument
      */
      static Function<T,T> identity() {
      return t -> t;
      }
      }

<span style="font-size:14px;">

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

}

//输出
5
4
LiLy
LiJin
111

Process finished with exit code 0


<span style="font-size:14px;">
<span style="font-size:14px;">
2、BiFunction<T,U,R>函数接口

/**

  • @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能力.

  • 函数功能:输入两个参数,返回一个结果.

  • This is a

  • whose functional method is {@link #apply(Object,Object)}.

  • @param the type of the first argument to the function

  • @param the type of the second argument to the function

  • @param the type of the result of the function

  • @see java.util.function.Function

  • @since 1.8
    */
    @FunctionalInterface
    public interface BiFunction<T,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,it is relayed to
    • the caller of the composed function.
    • addThen方法:返回一个组合函数.
    • 函数执行过程:先对输入参数执行apply函数,再对apply的结果执行after函数.
    • 如果执行过程中,任一函数发生异常,异常会被返回到组合函数的调用者这里.
    • @param 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 BiFunction<T,V> andThen(java.util.function.Function<? super R,? extends V> after) {
      Objects.requireNonNull(after);
      return (T t,U u) -> after.apply(apply(t,u));
      }
      }

<span style="font-size:14px;">


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> function1=(t,u)->t+u;
System.out.println(function1.andThen(String::new).apply("cao","xiao"));
}
}

//输出
7
caoxiao

Process finished with exit code 0


<span style="font-size:14px;">
<span style="font-size:14px;">
3、UnaryOperator函数接口

/**

  • @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.(这一点由其继承接口决定)

  • This is a

  • whose functional method is {@link #apply(Object)}.

  • @param the type of the operand and result of the operator

  • @see java.util.function.Function

  • @since 1.8
    */
    @FunctionalInterface
    public interface UnaryOperator extends java.util.function.Function<T,T> {

    /**

    • Returns a unary operator that always returns its input argument.
    • @param the type of the input and output of the operator
    • @return a unary operator that always returns its input argument
      */
      static UnaryOperator identity() {
      return t -> t;
      }
      }

<span style="font-size:14px;">
<span style="font-size:14px;">3.2、使用方法举例:
<code class="language-java"><span style="font-size:14px;">//UnaryOperator
import java.util.function.UnaryOperator;

public class Main {
public static void main(String[] args) {
//UnaryOperator
//1.功能函数:apply
UnaryOperator 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,T> 得到的
    UnaryOperator<Integer> uOpe3=integer -> integer+=2;
    System.out.println(uOpe3.andThen(Integer::highestOneBit).apply(100));
}

}

//输出
10
abc
65
64

Process finished with exit code 0


<span style="font-size:14px;">
4、BinaryOperator函数接口?

/**

  • @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嘛

  • This is a

  • whose functional method is {@link #apply(Object,Object)}.

  • @param the type of the operands and result of the operator

  • @see java.util.function.BiFunction

  • @see UnaryOperator

  • @since 1.8
    */
    @FunctionalInterface
    public interface BinaryOperator 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 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 BinaryOperator 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 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 BinaryOperator maxBy(Comparator<? super T> comparator) {
      Objects.requireNonNull(comparator);
      return (a,b) >= 0 ? a : b;
      }
      }

<span style="font-size:14px;">
<span style="font-size:14px;">4.2、使用方法举例:
<code class="language-java"><span style="font-size:14px;">//BinaryOperator
import java.util.Comparator;
import java.util.function.BinaryOperator;

public class Main {
public static void main(String[] args) {
//BinaryOperator
//1.功能方法:apply
BinaryOperator add=(x,y)->x+y;
System.out.println("add : "+add.apply(11,12));
//2.静态方法:minBy(Comparator<? super T> comparator)
Comparator 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 : 23
min : 1
max : 3

Process finished with exit code 0


<span style="font-size:14px;">
5、Predicate函数接口

/**

  • @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方法

  • This is a

  • whose functional method is {@link #test(Object)}.

  • @param the type of the input to the predicate

  • @since 1.8
    */
    @FunctionalInterface
    public interface Predicate {

    /**

    • 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条件
    • 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 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 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.
    • 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 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 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 Predicate isEqual(Object targetRef) {
      return (null == targetRef)
      ? Objects::isNull
      : object -> targetRef.equals(object);
      }
      }

<span style="font-size:14px;">
<span style="font-size:14px;">5.2、使用方法举例:
<code class="language-java"><span style="font-size:14px;">//Predicate



import java.util.function.Predicate;

public class Main {
public static void main(String[] args) {
//Predicate
//1.功能方法:test(T t)
Predicate 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 &amp;&amp; 字符串==lingye1234567
    System.out.println(pred2.and(pred1).test("cxh"));//要求字符串长度>10 &amp;&amp; 字符串==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));
}

}

//输出:
true
false
true
false
true
false
false
true
true
false

Process finished with exit code 0


<span style="font-size:14px;">
6、Consumer函数接口

/**

  • @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)

  • This is a

  • whose functional method is {@link #accept(Object)}.

  • @param the type of the input to the operation

  • @since 1.8
    */
    @FunctionalInterface
    public interface Consumer {

    /**

    • 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 consumer1=x->{System.out.println("consumer is :"+x+1);};
      Consumer 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 andThen(Consumer<? super T> after) {
      Objects.requireNonNull(after);
      return (T t) -> { accept(t); after.accept(t); };
      }
      }

<span style="font-size:14px;">
<span style="font-size:14px;">6.2、使用方法举例:
<code class="language-java"><span style="font-size:14px;">//Consumer
import java.util.function.Consumer;

public class Main {
public static void main(String[] args) {
//Consumer
//1.功能方法:accept(T t)
Consumer 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);
}

}

//输出
111
112
113

Process finished with exit code 0


<span style="font-size:14px;">
7、Supplier函数接口

/**

  • @Author: cxh

  • @CreateTime: 17/12/24 10:31

  • @ProjectName: JavaBaseTest
    */
    /**

  • Represents a supplier of results.

  • 这是一个提供结果的函数接口.

  • 特点:

  • (1)只有返回值

  • (2)没有输入参数

  • There is no requirement that a new or distinct result be returned each

  • time the supplier is invoked.

  • get()方法被调用时,对于一定要new出一个新对象 or 生成一个和之前结果不同的值 这两方面,都没有强制规定.

  • 这一接口函数的功能方法为:get()

  • This is a

  • whose functional method is {@link #get()}.

  • @param the type of results supplied by this supplier

  • @since 1.8
    */
    @FunctionalInterface
    public interface Supplier {

    /**

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

<span style="font-size:14px;">
<span style="font-size:14px;">7.2、使用方法举例:
<code class="language-java"><span style="font-size:14px;">//Supplier
import java.util.function.Supplier;

public class Main {
public static void main(String[] args) {
//Supplier
//1.功能函数:get()
Supplier supplier=()->"lingye";
System.out.println(supplier.get());
}
}

//输出
lingye

Process finished with exit code 0


<span style="font-size:14px;">

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读