如何在 Java 中迭代 lambda 函数

2022-09-05 00:33:39

我能够在Python中做到这一点,我的Python代码是:

signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}

a = 5
b = 3
for i in signs.keys():
    print(signs[i](a,b))

输出为:

8
2

我如何通过HashMap在Java中做同样的事情?


答案 1

您可以使用 BinaryOperator<Integer> 在这种情况下,如下所示:

BinaryOperator<Integer> add = (a, b) -> a + b;//lambda a, b : a + b
BinaryOperator<Integer> sub = (a, b) -> a - b;//lambda a, b : a - b

// Then create a new Map which take the sign and the corresponding BinaryOperator
// equivalent to signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}
Map<String, BinaryOperator<Integer>> signs = Map.of("+", add, "-", sub);

int a = 5; // a = 5
int b = 3; // b = 3

// Loop over the sings map and apply the operation
signs.values().forEach(v -> System.out.println(v.apply(a, b)));

输出

8
2

注意,我正在使用Java 10,如果您没有使用Java 9 +,则可以像这样添加到您的地图中:Map.of("+", add, "-", sub);

Map<String, BinaryOperator<Integer>> signs = new HashMap<>();
signs.put("+", add);
signs.put("-", sub);

Ideone demo


良好做法

正如@Boris蜘蛛和@Holger在注释中已经说过的那样,最好使用它来避免装箱,最后你的代码可以看起来像这样:IntBinaryOperator

// signs = {"+" : lambda a, b : a + b, "-" : lambda a, b : a - b}
Map<String, IntBinaryOperator> signs = Map.of("+", (a, b) -> a + b, "-", (a, b) -> a - b);
int a = 5; // a = 5
int b = 3; // b = 3
// for i in signs.keys(): print(signs[i](a,b))
signs.values().forEach(v -> System.out.println(v.applyAsInt(a, b)));

答案 2

为自己创造一个漂亮的,安全的, :enum

enum Operator implements IntBinaryOperator {
    PLUS("+", Integer::sum),
    MINUS("-", (a, b) -> a - b);

    private final String symbol;
    private final IntBinaryOperator op;

    Operator(final String symbol, final IntBinaryOperator op) {
        this.symbol = symbol;
        this.op = op;
    }

    public String symbol() {
        return symbol;
    }

    @Override
    public int applyAsInt(final int left, final int right) {
        return op.applyAsInt(left, right);
    }
}

您可能需要一个返回的 lambda,而不是返回其他运算符。doubleint

现在,只需将其转储到:Map

final var operators = Arrays.stream(Operator.values())
        .collect(toMap(Operator::symbol, identity()));

但是,对于您的示例,您根本不需要:Map

Arrays.stream(Operator.values())
        .mapToInt(op -> op.applyAsInt(a,b))
        .forEach(System.out::println);

用:

import static java.util.function.Function.identity;
import static java.util.stream.Collectors.toMap;