Jum*_*p3r 15 lambda containers binary-operators lookup-tables java-8
我想知道是否可以将lambda存放在某个容器中,例如.ArrayList或HashMap.我想更改该代码:
public enum OPCODE implements BinaryOperator<Integer> {
MOV((x, y) -> y),
INC((x, y) -> ++x),
DEC((x, y) -> --x),
ADD((x, y) -> x + y),
SUB((x, y) -> x - y);
private final BinaryOperator<Integer> binaryOperator;
OPCODE(BinaryOperator<Integer> binaryOperator) {
this.binaryOperator = binaryOperator;
}
@Override
public Integer apply(Integer integer, Integer integer2) {
return binaryOperator.apply(integer, integer2);
}
}
Run Code Online (Sandbox Code Playgroud)
对于这样的事情:
List<BinaryOperator<Integer>> opcodes = new ArrayList<BinaryOperator<Integer>>(){
((x, y) -> y),
((x, y) -> ++x)
};
Run Code Online (Sandbox Code Playgroud)
等等
并像这样使用它:
opcodes[0].apply(a, b);
Run Code Online (Sandbox Code Playgroud)
甚至可能吗?
Nam*_*man 12
你当然可以创建如下列表:
List<BinaryOperator<Integer>> opcodes = Arrays.asList((x, y) -> y, (x, y) -> ++x);
// sample
int a=14,b=16;
System.out.println(opcodes.get(0).apply(a, b)); // prints 16
System.out.println(opcodes.get(1).apply(a, b)); // prints 15
Run Code Online (Sandbox Code Playgroud)
或者纠正您尝试初始化列表的方式
List<BinaryOperator<Integer>> opcodes = new ArrayList<BinaryOperator<Integer>>() {{
add((x, y) -> y);
add((x, y) -> ++x);
add((x, y) -> --x);
add((x, y) -> x + y);
add((x, y) -> x - y);
}};
Run Code Online (Sandbox Code Playgroud)
在@ nullpointer的另外一个很好的答案中,您还可以考虑使用一个Map
键来保留OPCODE
函数的初始意图,这些函数在数组中是最小的,例如使用Enum
一个键作为键:
public enum OPCODES {
MOV, ADD, XOR
}
Run Code Online (Sandbox Code Playgroud)
哪个可以自助:
Map<OPCODES, BinaryOperator<Integer>> opcodeMap =
new EnumMap<OPCODES, BinaryOperator<Integer>>(OPCODES.class);
opcodeMap.put(OPCODES.ADD, (x, y)-> x + y);
opcodeMap.put(OPCODES.MOV, (x, y) -> y);
opcodeMap.put(OPCODES.XOR, (x, y) -> x ^ y);
Run Code Online (Sandbox Code Playgroud)
用过:
System.out.println(opcodeMap.get(OPCODES.ADD).apply(1, 2));
System.out.println(opcodeMap.get(OPCODES.MOV).apply(1, 2));
System.out.println(opcodeMap.get(OPCODES.XOR).apply(1, 2));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2335 次 |
最近记录: |