lambdajava-8containerslookup-tablesbinary-operators

Java 8 - store lambdas in List


I wonder if it's possible to store lambdas in some container, for ex. ArrayList or HashMap. I want to change that code:

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);
    }
}

To something like:

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

etc.

and use it like so:

opcodes[0].apply(a, b);

It is even possible?


Solution

  • You can certainly create such a list as:

    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
    

    Or redressing the way you were trying to initializing the list

    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);
    }};