Java8 lamda,Function

Lamda/Function

lamda表达式

首先介绍下lamda表达式,java1.8开始加入的。

new Thread(()-> {

}).start();

findViewById(R.id.firstBtn).setOnClickListener((v)-> {
  //xxxx
});

int x = (i)-> i * i;

我们在android开发中会经常看到这样的提示。

这就是lamda表达式的格式。

定义一个lamda函数式接口

一个接口Interface,需要满足"有且仅有一个抽象方法",@FunctionInterface注解只起到辅助检查作用,如果只有一个函数的接口,就可以当做lamda表达式。

@FunctionalInterface
public interface Runnable {
    public void run();
}

public interface IConverter {
    public String convert(int i);
}
Function

Function<T, R> 来申明一个函数变量。简单来讲,就是把一种处理参数想拿结果的函数体,当做参数变量来使用。或者用来定义lamda表达式。

他有几个方法:

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

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

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

compose组成的意思,等价于,在执行之前先执行它得到一个结果,再将这个结果去执行主体;

andThen则表示,在主体执行以后将中间结果给到它再去执行。

那好,现在真正的挑战来了:

f1.andThen(f2).compose(f3).andThen(f4).andThen(f5).compose(f6).apply(10);

执行顺序?(手动狗头)。

    Function<Integer, Integer> f1 = (x)-> {
        return x * x;
    };
    Function<Integer, Integer> f2 = (x)-> {
        System.out.println("f222");
        return x + x;
    };

    Function<Integer, Integer> f3 = (x)-> {
        System.out.println("f333");
        return x + 2*x;
    };

    Function<Integer, Integer> f4 = (x)-> {
        System.out.println("f444");
        return x * x;
    };
    Function<Integer, Integer> f5 = (x)-> {
        System.out.println("f555");
        return x + x;
    };

    Function<Integer, Integer> f6 = (x)-> {
        System.out.println("f666");
        return x + 2*x;
    };

好推理,不如好log。添加日志。很容易就看出来了。

f666
f333
f111
f222
f444
f555

因此,我们观察规律,f1.andThen(f2).compose(f3).andThen(f4).andThen(f5).compose(f6).apply(10);

规律就是:

先从右边倒过来一个个执行compose的Function(f6, f3),再执行本体(再f1),再从左边找andThen顺序执行(即f2, f4, f5)。
再次调整compose,andThen代码位置,验证正确。

之所以想了解下Function,其实想对比下C#中的Action比较类似。
其实还可以在rxjava中发现也有一个Function,甚至有Function2~Function9,多达9个参数的Function目的就是类似Action适配参数。
static的identity()不做解释了,可以自行百度。

另外,
rxjava中定义了一个简单的Function,只有apply(x)。也可以拿到当做lamda或者函数引用使用。
参考:https://blog.csdn.net/linjpg/article/details/102544027
https://www.runoob.com/java/java8-lambda-expressions.html
https://www.runoob.com/java/java8-functional-interfaces.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值