java8 lambda表达式 map,Java 8:使用lambda表达式的HashMap初始化

在尝试使用Lambda表达式一次性初始化HashMap时遇到了Eclipse的错误提示。问题出现在将Lambda表达式作为HashMap的值时,代码引发了语法错误。错误信息表明逗号被误认为是名称或表达式。解决方案是导入`Callable`接口并将Lambda表达式改为匿名内部类,以正确创建能够调用`call()`的方法。最终代码成功实现了预期功能,打印出HashMap中对应的值。
摘要由CSDN通过智能技术生成

I'm trying to declare and define larger hash map at once. This is how I do it:

public HashMap> opcode_only = new HashMap>() {{

put(x, y);

put(x, y);

}};

But, when I try to use lambda expressions in body of put, I'm hitting on eclipse warrning/error. This is how I use lambda in HashMap:

public HashMap> opcode_only = new HashMap>() {{

put(0, () -> { return "nop"; });

put(1, () -> { return "nothing...."; });

}};

Eclipse underlines whole part of lambda starting with comma before.

Error messages:

Syntax error on token ",", Name expected

Syntax error on tokens, Expression expected instead

Does anybody know what am I doing wrong? Is initialization by lambda expression allowed in HashMap? Please help.

解决方案

import java.util.*;

import java.util.concurrent.Callable;

public class StackoverFlowQuery {

public static void main(String[] args) throws Exception {

HashMap> opcode_only =

new HashMap>() {

{

put(0, () -> {

return "nop";

});

put(1, () -> {

return "nothing....";

});

}

};

System.out.println(opcode_only.get(0).call());

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值