java中lambada表达式中的Funtion

我们来看Function里面的方法
这里Fuction里面的方法
首先我们来看Apply的方法:

给定一个参数返回一个结果

    /**
     * Applies this function to the given argument.
     *
     * @param t the function argument
     * @return the function result
     */
    R apply(T t);

我们可以使用:
这个方法很简单,给定一个x参数,返回一个计算后的结果,这里泛型中左边Integer代表入参,右边的Integer代表返回类型。
还要注意的一点事 方法名称不要与Fuction中的方法同名,否则编译不通过。

	static Function<Integer,Integer> applys= (x)->{
	     return x+2;
	};
//调用的时候我们可以这样写:
 Integer apply2 = applys.apply(12);
 返回结果:14

我们来看第二个方法 compose:

   default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
       Objects.requireNonNull(before);
       return (V v) -> apply(before.apply(v));
   }

这个方法是给定一个Fuction的参数,返回一个Fuction的结果。
相当于函数结果会合并,比如说 第一个函数式f(x)=x+1;第二个函数发f(y)=x2;那么使用compse在前的就会把y代入f(x)=x+1中,从使得式子变成f(x)=(x2)+1;
例如如下:

	static Function<Integer,Integer> plus = (x)->{
	    return x+1;
	};

	static Function<Integer,Integer> multip = (x)->{
	    return x*2;
	};

使用的时候就是这样:

   // 此处执行的就是1*2+1=3  (x*2)+1 谁在前就把后面的公式代入第一个前面公式中得到计算结果    
    Integer applys = plus.compose(multip).apply(1); 

然后接下来看anthen:

default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
    Objects.requireNonNull(after);
    return (T t) -> after.apply(apply(t));
}

andthen跟compose相反,这里就不做说明。
还有一个identity:

  static <T> Function<T, T> identity() {
        return t -> t;
    }

dentity()就是Function接口的一个静态方法,输入一个参数返回一个Function对象,方便用返回的结果来使用Function中其他的方法。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值