Java 8:使用lambda表达式的HashMap初始化 [英] Java 8: HashMap initialization with lambda expressions
问题描述
我试图声明和一次定义更大的散列图。这是我怎么做的:
public HashMap< Integer,Callable< String> opcode_only = new HashMap< Integer,Callable< String>>(){{
put(x,y);
put(x,y);
}};但是,当我尝试在中使用lambda表达式 c code>,我打eclipse warrning /错误。这是我在HashMap中使用lambda的方法: public HashMap< Integer,Callable< String> opcode_only = new HashMap< Integer,Callable< String>>(){{
put(0,() - > {returnnop;});
put(1,() - > {returnnothing ....;});
}};
Eclipse以逗号开头的整个lambda部分。
错误消息:
令牌上的语法错误,,名称预期
tokens上的语法错误,表示期望而不是
有人知道我做错了什么?是否允许在 HashMap
中使用lambda表达式进行初始化?请帮助。
解决方案这在Netbeans Lamba版本中可以正常下载:http://bertram2.netbeans.org:8080/job/jdk8lambda/lastSuccessfulBuild/artifact/nbbuild/
import java.util。*;
import java.util.concurrent.Callable;
public class StackoverFlowQuery {
public static void main(String [] args)throws Exception {
HashMap< Integer,Callable< String> ; opcode_only =
new HashMap< Integer,Callable< String>>(){
{
put(0,() - > {
returnnop;
});
put(1,() - > {
returnnothing ....;
});
}
};
System.out.println(opcode_only.get(0).call());
}
}
I'm trying to declare and define larger hash map at once. This is how I do it:
public HashMap<Integer, Callable<String>> opcode_only = new HashMap<Integer, Callable<String>>() {{
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<Integer, Callable<String>> opcode_only = new HashMap<Integer, Callable<String>>() {{
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.
解决方案 This works fine in the Netbeans Lamba builds downloaded from: http://bertram2.netbeans.org:8080/job/jdk8lambda/lastSuccessfulBuild/artifact/nbbuild/
import java.util.*;
import java.util.concurrent.Callable;
public class StackoverFlowQuery {
public static void main(String[] args) throws Exception {
HashMap<Integer, Callable<String>> opcode_only =
new HashMap<Integer, Callable<String>>() {
{
put(0, () -> {
return "nop";
});
put(1, () -> {
return "nothing....";
});
}
};
System.out.println(opcode_only.get(0).call());
}
}
这篇关于Java 8:使用lambda表达式的HashMap初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!