lambda - Java 8 - 在 List 中存储 lambdas

标签 lambda java-8 containers lookup-tables binary-operators

我想知道是否可以将 lambdas 存储在某个容器中,例如。 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);
    }
}

类似于:
List<BinaryOperator<Integer>> opcodes = new ArrayList<BinaryOperator<Integer>>(){
    ((x, y) -> y),
    ((x, y) -> ++x)
};

等等。

并像这样使用它:
opcodes[0].apply(a, b);

甚至有可能吗?

最佳答案

您当然可以创建这样的列表:

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

或纠正您尝试初始化列表的方式
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);
}};

关于lambda - Java 8 - 在 List 中存储 lambdas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46987666/

相关文章:

docker - 使用 docker 安装 java 8 的最佳方法?

Azure IoT Edge 部署文件已更新但已删除 docker 容器仍保持运行

c# - 对字符串中存在特定字符的列表进行排序

python - 从多个列表和变量构建一个复杂的 python 字典

java - 你能把一个流分成两个流吗?

Java 8 并行流并发分组

mysql - 在互联网上公开本地 Docker 容器(有两个容器相互链接)。

javascript - 你能在浏览器中执行包含的 JavaScript 吗?

c# - 将 lambda 字符串表达式转换为 Func<string, string> 错误 : "No property or field ' v' exists in type 'String' "

c# - 为什么 C# lambda 表达式不能包含一个简单的 if 语句,而不需要大括号?