java 数组 lambda,在Java中声明Lambda数组

I'd like to create an array of lambda. The problem is that the lambda could be different from each other. Example:

private interface I0 {

int interface0(int a, int b);

}

private interface I1 {

int interface1(double d);

}

Now, how can I declare a list which can contain both I0 and I1?

List test = Arrays.asList(

(int a, int b) -> a + b,

(double d) -> d * 2

);

Obviously Object does not work.

解决方案

You must assign the lambda expressions to variables of the functional interface types first.

Otherwise the compiler cannot infer the types of these lambda expressions.

I0 i0 = (int a, int b) -> a + b;

I1 i1 = (double d) -> (int) (d * 2);

List test = Arrays.asList(

i0,

i1

);

That said, I'm not sure what's the point of storing these lambda expressions in a List. You can't use them without casting them back to the individual functional interface types.

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值